coverage-report

Code coverage report for All files

npmtest-lighthouse (v0.0.1)

Code coverage report for All files

Statements: 21.67% (3401 / 15696)      Branches: 5.99% (347 / 5793)      Functions: 12.17% (330 / 2711)      Lines: 30.93% (977 / 3159)      Ignored: 42 statements, 4 functions, 33 branches     

File Statements Branches Functions Lines
node-npmtest-lighthouse/ 100% (153 / 153) 100% (126 / 126) 100% (28 / 28) 100% (153 / 153)
node-npmtest-lighthouse/node_modules/lighthouse/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/ 47.84% (232 / 485) 23.67% (40 / 169) 39.22% (20 / 51) 49.46% (230 / 465)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/commands/ 65% (13 / 20) 100% (0 / 0) 0% (0 / 2) 68.42% (13 / 19)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/ 19.51% (16 / 82) 0% (0 / 16) 0% (0 / 5) 20.25% (16 / 79)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/experiment-database/ 26.32% (5 / 19) 100% (0 / 0) 0% (0 / 7) 26.32% (5 / 19)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/report/ 46.15% (6 / 13) 100% (0 / 0) 0% (0 / 2) 46.15% (6 / 13)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/ 14.96% (19 / 127) 0% (0 / 58) 0% (0 / 7) 15.2% (19 / 125)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/aggregator/ 1.69% (1 / 59) 0% (0 / 32) 0% (0 / 9) 1.79% (1 / 56)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/ 22.42% (74 / 330) 0% (0 / 128) 0% (0 / 61) 22.77% (74 / 325)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/closure/ 10% (1 / 10) 0% (0 / 2) 0% (0 / 1) 10% (1 / 10)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/config/ 9.14% (16 / 175) 0% (0 / 103) 0% (0 / 16) 9.47% (16 / 169)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/ 21.05% (28 / 133) 0% (0 / 69) 0% (0 / 20) 21.37% (28 / 131)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/ 3.92% (19 / 485) 0% (0 / 163) 2.74% (2 / 73) 4.05% (19 / 469)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/connections/ 11.58% (11 / 95) 0% (0 / 22) 0% (0 / 15) 11.7% (11 / 94)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/gatherers/ 50% (1 / 2) 100% (0 / 0) 0% (0 / 4) 50% (1 / 2)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/ 30.51% (187 / 613) 11.21% (26 / 232) 10.16% (13 / 128) 30.86% (187 / 606)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/traces/ 12.5% (19 / 152) 9.62% (5 / 52) 6.25% (1 / 16) 12.84% (19 / 148)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/report/ 12.28% (14 / 114) 0% (0 / 48) 0% (0 / 19) 12.5% (14 / 112)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ 100% (4 / 4) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/ 30.01% (858 / 2859) 11.73% (125 / 1066) 21.58% (112 / 519) 100% (32 / 32)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/core/ 40.68% (24 / 59) 0% (0 / 19) 9.52% (2 / 21) 100% (2 / 2)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/ 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/chrome/ 68.29% (28 / 41) 20% (2 / 10) 60% (3 / 5) 100% (1 / 1)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/chrome/cc/ 9.69% (25 / 258) 0% (0 / 151) 6.06% (2 / 33) 100% (1 / 1)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/ 5.3% (77 / 1452) 0% (0 / 790) 2.86% (3 / 105) 100% (3 / 3)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/v8/ 21.77% (54 / 248) 0% (0 / 87) 4.08% (2 / 49) 100% (2 / 2)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/ 14.4% (159 / 1104) 0% (0 / 365) 4.89% (9 / 184) 100% (9 / 9)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/ 29.28% (65 / 222) 3.85% (2 / 52) 27.27% (6 / 22) 100% (5 / 5)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/blink/ 30.38% (24 / 79) 0% (0 / 6) 5.26% (1 / 19) 100% (1 / 1)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/ 21.73% (196 / 902) 0% (0 / 303) 8.8% (11 / 125) 100% (11 / 11)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/v8/ 24.11% (95 / 394) 0% (0 / 58) 6.06% (4 / 66) 100% (4 / 4)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/ 18.77% (637 / 3393) 0.76% (8 / 1059) 7.88% (61 / 774) 100% (55 / 55)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/ 24% (54 / 225) 0% (0 / 80) 8.93% (5 / 56) 100% (5 / 5)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/source_info/ 30.77% (12 / 39) 0% (0 / 16) 15.38% (2 / 13) 100% (2 / 2)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/ 45.77% (65 / 142) 7.14% (2 / 28) 20% (8 / 40) 100% (7 / 7)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/annotations/ 30.77% (24 / 78) 0% (0 / 10) 30.77% (4 / 13) 100% (4 / 4)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/base/ 13.24% (27 / 204) 1.25% (1 / 80) 8.82% (3 / 34) 100% (3 / 3)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/ 13.35% (59 / 442) 2.86% (6 / 210) 15.87% (10 / 63) 100% (2 / 2)
node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/ 19.96% (96 / 481) 2.19% (4 / 183) 16.98% (18 / 106) 100% (12 / 12)
Code coverage report for node-npmtest-lighthouse/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/

Statements: 100% (153 / 153)      Branches: 100% (126 / 126)      Functions: 100% (28 / 28)      Lines: 100% (153 / 153)      Ignored: 26 statements, 1 function, 30 branches     

All files » node-npmtest-lighthouse/
File Statements Branches Functions Lines
example.js 100% (83 / 83) 100% (73 / 73) 100% (12 / 12) 100% (83 / 83)
lib.npmtest_lighthouse.js 100% (16 / 16) 100% (14 / 14) 100% (3 / 3) 100% (16 / 16)
test.js 100% (54 / 54) 100% (39 / 39) 100% (13 / 13) 100% (54 / 54)
Code coverage report for node-npmtest-lighthouse/example.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/example.js

Statements: 100% (83 / 83)      Branches: 100% (73 / 73)      Functions: 100% (12 / 12)      Lines: 100% (83 / 83)      Ignored: 26 statements, 1 function, 30 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328                                                  2   2         2   2   2 2 2         1             2       2       2   2               1 2           2     2     2 2   1       2     1 1 1   1 1     1 1   1     1   2           1   1   1         1 2 2 3 3 3 3 1     3 3         3       1 3 1       1 1               1   1 1 1   1   1                                                                                                                                                                                       1 1                       1     6 6   1   2   1   2         1 1   1         1             1     1 1     1 1   1 1 1 1 1 1 1   1 1   1        
/*
example.js
 
quickstart example
 
instruction
    1. save this script as example.js
    2. run the shell command:
        $ npm install npmtest-lighthouse && PORT=8081 node example.js
    3. play with the browser-demo on http://127.0.0.1:8081
*/
 
 
 
/* istanbul instrument in package npmtest_lighthouse */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        // init utility2_rollup
        local = local.global.utility2_rollup || (local.modeJs === 'browser'
            ? local.global.utility2_npmtest_lighthouse
            : global.utility2_moduleExports);
        // export local
        local.global.local = local;
    }());
    switch (local.modeJs) {
 
 
 
    // post-init
    // run browser js-env code - post-init
    /* istanbul ignore next */
    case 'browser':
        local.testRunBrowser = function (event) {
            Eif (!event || (event &&
                    event.currentTarget &&
                    event.currentTarget.className &&
                    event.currentTarget.className.includes &&
                    event.currentTarget.className.includes('onreset'))) {
                // reset output
                Array.from(
                    document.querySelectorAll('body > .resettable')
                ).forEach(function (element) {
                    switch (element.tagName) {
                    case 'INPUT':
                    case 'TEXTAREA':
                        element.value = '';
                        break;
                    default:
                        element.textContent = '';
                    }
                });
            }
            switch (event && event.currentTarget && event.currentTarget.id) {
            case 'testRunButton1':
                // show tests
                Eif (document.querySelector('#testReportDiv1').style.display === 'none') {
                    document.querySelector('#testReportDiv1').style.display = 'block';
                    document.querySelector('#testRunButton1').textContent =
                        'hide internal test';
                    local.modeTest = true;
                    local.testRunDefault(local);
                // hide tests
                } else {
                    document.querySelector('#testReportDiv1').style.display = 'none';
                    document.querySelector('#testRunButton1').textContent = 'run internal test';
                }
                break;
            // custom-case
            default:
                break;
            }
            Iif (document.querySelector('#inputTextareaEval1') && (!event || (event &&
                    event.currentTarget &&
                    event.currentTarget.className &&
                    event.currentTarget.className.includes &&
                    event.currentTarget.className.includes('oneval')))) {
                // try to eval input-code
                try {
                    /*jslint evil: true*/
                    eval(document.querySelector('#inputTextareaEval1').value);
                } catch (errorCaught) {
                    console.error(errorCaught);
                }
            }
        };
        // log stderr and stdout to #outputTextareaStdout1
        ['error', 'log'].forEach(function (key) {
            console[key + '_original'] = console[key];
            console[key] = function () {
                var element;
                console[key + '_original'].apply(console, arguments);
                element = document.querySelector('#outputTextareaStdout1');
                Iif (!element) {
                    return;
                }
                // append text to #outputTextareaStdout1
                element.value += Array.from(arguments).map(function (arg) {
                    return typeof arg === 'string'
                        ? arg
                        : JSON.stringify(arg, null, 4);
                }).join(' ') + '\n';
                // scroll textarea to bottom
                element.scrollTop = element.scrollHeight;
            };
        });
        // init event-handling
        ['change', 'click', 'keyup'].forEach(function (event) {
            Array.from(document.querySelectorAll('.on' + event)).forEach(function (element) {
                element.addEventListener(event, local.testRunBrowser);
            });
        });
        // run tests
        local.testRunBrowser();
        break;
 
 
 
    // run node js-env code - post-init
    /* istanbul ignore next */
    case 'node':
        // export local
        module.exports = local;
        // require modules
        local.fs = require('fs');
        local.http = require('http');
        local.url = require('url');
        // init assets
        local.assetsDict = local.assetsDict || {};
        /* jslint-ignore-begin */
        local.assetsDict['/assets.index.template.html'] = '\
<!doctype html>\n\
<html lang="en">\n\
<head>\n\
<meta charset="UTF-8">\n\
<meta name="viewport" content="width=device-width, initial-scale=1">\n\
<title>{{env.npm_package_name}} (v{{env.npm_package_version}})</title>\n\
<style>\n\
/*csslint\n\
    box-sizing: false,\n\
    universal-selector: false\n\
*/\n\
* {\n\
    box-sizing: border-box;\n\
}\n\
body {\n\
    background: #dde;\n\
    font-family: Arial, Helvetica, sans-serif;\n\
    margin: 2rem;\n\
}\n\
body > * {\n\
    margin-bottom: 1rem;\n\
}\n\
.utility2FooterDiv {\n\
    margin-top: 20px;\n\
    text-align: center;\n\
}\n\
</style>\n\
<style>\n\
/*csslint\n\
*/\n\
textarea {\n\
    font-family: monospace;\n\
    height: 10rem;\n\
    width: 100%;\n\
}\n\
textarea[readonly] {\n\
    background: #ddd;\n\
}\n\
</style>\n\
</head>\n\
<body>\n\
<!-- utility2-comment\n\
<div id="ajaxProgressDiv1" style="background: #d00; height: 2px; left: 0; margin: 0; padding: 0; position: fixed; top: 0; transition: background 0.5s, width 1.5s; width: 25%;"></div>\n\
utility2-comment -->\n\
<h1>\n\
<!-- utility2-comment\n\
    <a\n\
        {{#if env.npm_package_homepage}}\n\
        href="{{env.npm_package_homepage}}"\n\
        {{/if env.npm_package_homepage}}\n\
        target="_blank"\n\
    >\n\
utility2-comment -->\n\
        {{env.npm_package_name}} (v{{env.npm_package_version}})\n\
<!-- utility2-comment\n\
    </a>\n\
utility2-comment -->\n\
</h1>\n\
<h3>{{env.npm_package_description}}</h3>\n\
<!-- utility2-comment\n\
<h4><a download href="assets.app.js">download standalone app</a></h4>\n\
<button class="onclick onreset" id="testRunButton1">run internal test</button><br>\n\
<div id="testReportDiv1" style="display: none;"></div>\n\
utility2-comment -->\n\
\n\
\n\
\n\
<label>stderr and stdout</label>\n\
<textarea class="resettable" id="outputTextareaStdout1" readonly></textarea>\n\
<!-- utility2-comment\n\
{{#if isRollup}}\n\
<script src="assets.app.js"></script>\n\
{{#unless isRollup}}\n\
utility2-comment -->\n\
<script src="assets.utility2.rollup.js"></script>\n\
<script src="jsonp.utility2._stateInit?callback=window.utility2._stateInit"></script>\n\
<script src="assets.npmtest_lighthouse.rollup.js"></script>\n\
<script src="assets.example.js"></script>\n\
<script src="assets.test.js"></script>\n\
<!-- utility2-comment\n\
{{/if isRollup}}\n\
utility2-comment -->\n\
<div class="utility2FooterDiv">\n\
    [ this app was created with\n\
    <a href="https://github.com/kaizhu256/node-utility2" target="_blank">utility2</a>\n\
    ]\n\
</div>\n\
</body>\n\
</html>\n\
';
        /* jslint-ignore-end */
        Iif (local.templateRender) {
            local.assetsDict['/'] = local.templateRender(
                local.assetsDict['/assets.index.template.html'],
                {
                    env: local.objectSetDefault(local.env, {
                        npm_package_description: 'the greatest app in the world!',
                        npm_package_name: 'my-app',
                        npm_package_nameAlias: 'my_app',
                        npm_package_version: '0.0.1'
                    })
                }
            );
        } else {
            local.assetsDict['/'] = local.assetsDict['/assets.index.template.html']
                .replace((/\{\{env\.(\w+?)\}\}/g), function (match0, match1) {
                    // jslint-hack
                    String(match0);
                    switch (match1) {
                    case 'npm_package_description':
                        return 'the greatest app in the world!';
                    case 'npm_package_name':
                        return 'my-app';
                    case 'npm_package_nameAlias':
                        return 'my_app';
                    case 'npm_package_version':
                        return '0.0.1';
                    }
                });
        }
        // run the cli
        Eif (local.global.utility2_rollup || module !== require.main) {
            break;
        }
        local.assetsDict['/assets.example.js'] =
            local.assetsDict['/assets.example.js'] ||
            local.fs.readFileSync(__filename, 'utf8');
        // bug-workaround - long $npm_package_buildCustomOrg
        /* jslint-ignore-begin */
        local.assetsDict['/assets.npmtest_lighthouse.rollup.js'] =
            local.assetsDict['/assets.npmtest_lighthouse.rollup.js'] ||
            local.fs.readFileSync(
                local.npmtest_lighthouse.__dirname + '/lib.npmtest_lighthouse.js',
                'utf8'
            ).replace((/^#!/), '//');
        /* jslint-ignore-end */
        local.assetsDict['/favicon.ico'] = local.assetsDict['/favicon.ico'] || '';
        // if $npm_config_timeout_exit exists,
        // then exit this process after $npm_config_timeout_exit ms
        if (Number(process.env.npm_config_timeout_exit)) {
            setTimeout(process.exit, Number(process.env.npm_config_timeout_exit));
        }
        // start server
        if (local.global.utility2_serverHttp1) {
            break;
        }
        process.env.PORT = process.env.PORT || '8081';
        console.error('server starting on port ' + process.env.PORT);
        local.http.createServer(function (request, response) {
            request.urlParsed = local.url.parse(request.url);
            if (local.assetsDict[request.urlParsed.pathname] !== undefined) {
                response.end(local.assetsDict[request.urlParsed.pathname]);
                return;
            }
            response.statusCode = 404;
            response.end();
        }).listen(process.env.PORT);
        break;
    }
}());
 
 
Code coverage report for node-npmtest-lighthouse/lib.npmtest_lighthouse.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/lib.npmtest_lighthouse.js

Statements: 100% (16 / 16)      Branches: 100% (14 / 14)      Functions: 100% (3 / 3)      Lines: 100% (16 / 16)      Ignored: none     

All files » node-npmtest-lighthouse/ » lib.npmtest_lighthouse.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55                      2   2         2   2   2 2 2         1             2       2   2   2 1   1 1 1          
/* istanbul instrument in package npmtest_lighthouse */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        // init utility2_rollup
        local = local.global.utility2_rollup || local;
        // init lib
        local.local = local.npmtest_lighthouse = local;
        // init exports
        if (local.modeJs === 'browser') {
            local.global.utility2_npmtest_lighthouse = local;
        } else {
            module.exports = local;
            module.exports.__dirname = __dirname;
            module.exports.module = module;
        }
    }());
}());
 
 
Code coverage report for node-npmtest-lighthouse/test.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/test.js

Statements: 100% (54 / 54)      Branches: 100% (39 / 39)      Functions: 100% (13 / 13)      Lines: 100% (54 / 54)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197                      2   2         2   2   2 2 2         1             2     2     1       1     1   1     2           2 2   2           1           1           2 2   2           1             1       1     1             1             1 1     1             1 1 1 1 1 1     1         2 2     1             2 2     1             2 2     1             2 2     1             1 1       1 1        
/* istanbul instrument in package npmtest_lighthouse */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        switch (local.modeJs) {
        // re-init local from window.local
        case 'browser':
            local = local.global.utility2.objectSetDefault(
                local.global.utility2_rollup || local.global.local,
                local.global.utility2
            );
            break;
        // re-init local from example.js
        case 'node':
            local = (local.global.utility2_rollup || require('utility2'))
                .requireReadme();
            break;
        }
        // export local
        local.global.local = local;
    }());
 
 
 
    // run shared js-env code - function
    (function () {
        return;
    }());
    switch (local.modeJs) {
 
 
 
    // run browser js-env code - function
    case 'browser':
        break;
 
 
 
    // run node js-env code - function
    case 'node':
        break;
    }
 
 
 
    // run shared js-env code - post-init
    (function () {
        return;
    }());
    switch (local.modeJs) {
 
 
 
    // run browser js-env code - post-init
    case 'browser':
        local.testCase_browser_nullCase = local.testCase_browser_nullCase || function (
            options,
            onError
        ) {
        /*
         * this function will test browsers's null-case handling-behavior-behavior
         */
            onError(null, options);
        };
 
        // run tests
        local.nop(local.modeTest &&
            document.querySelector('#testRunButton1') &&
            document.querySelector('#testRunButton1').click());
        break;
 
 
 
    // run node js-env code - post-init
    /* istanbul ignore next */
    case 'node':
        local.testCase_buildApidoc_default = local.testCase_buildApidoc_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildApidoc's default handling-behavior-behavior
         */
            options = { modulePathList: module.paths };
            local.buildApidoc(options, onError);
        };
 
        local.testCase_buildApp_default = local.testCase_buildApp_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildApp's default handling-behavior-behavior
         */
            local.testCase_buildReadme_default(options, local.onErrorThrow);
            local.testCase_buildLib_default(options, local.onErrorThrow);
            local.testCase_buildTest_default(options, local.onErrorThrow);
            local.testCase_buildCustomOrg_default(options, local.onErrorThrow);
            options = [];
            local.buildApp(options, onError);
        };
 
        local.testCase_buildCustomOrg_default = local.testCase_buildCustomOrg_default ||
            function (options, onError) {
            /*
             * this function will test buildCustomOrg's default handling-behavior
             */
                options = {};
                local.buildCustomOrg(options, onError);
            };
 
        local.testCase_buildLib_default = local.testCase_buildLib_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildLib's default handling-behavior
         */
            options = {};
            local.buildLib(options, onError);
        };
 
        local.testCase_buildReadme_default = local.testCase_buildReadme_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildReadme's default handling-behavior-behavior
         */
            options = {};
            local.buildReadme(options, onError);
        };
 
        local.testCase_buildTest_default = local.testCase_buildTest_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildTest's default handling-behavior
         */
            options = {};
            local.buildTest(options, onError);
        };
 
        local.testCase_webpage_default = local.testCase_webpage_default || function (
            options,
            onError
        ) {
        /*
         * this function will test webpage's default handling-behavior
         */
            options = { modeCoverageMerge: true, url: local.serverLocalHost + '?modeTest=1' };
            local.browserTest(options, onError);
        };
 
        // run test-server
        local.testRunServer(local);
        break;
    }
}());
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/
File Statements Branches Functions Lines
.eslintrc.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/.eslintrc.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/.eslintrc.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 591                                                                                                                    
module.exports = {
  // start with google standard style
  //     https://github.com/google/eslint-config-google/blob/master/index.js
  "extends": ["eslint:recommended", "google"],
  "env": {
    "node": true,
    "es6": true
  },
  "rules": {
    // 2 == error, 1 == warning, 0 == off
    "indent": [2, 2, {
      "SwitchCase": 1,
      "VariableDeclarator": 2
    }],
    "max-len": [2, 100, {
      "ignoreComments": true,
      "ignoreUrls": true,
      "tabWidth": 2
    }],
    "no-empty": [2, {
      "allowEmptyCatch": true
    }],
    "no-implicit-coercion": [2, {
      "boolean": false,
      "number": true,
      "string": true
    }],
    "no-unused-expressions": [2, {
      "allowShortCircuit": true,
      "allowTernary": false
    }],
    "no-unused-vars": [2, {
      "vars": "all",
      "args": "after-used",
      "argsIgnorePattern": "(^reject$|^_$)",
      "varsIgnorePattern": "(^_$)"
    }],
    "quotes": [2, "single"],
    "strict": [2, "global"],
    "prefer-const": 2,
 
    // Disabled rules
    "require-jsdoc": 0,
    "valid-jsdoc": 0,
    "comma-dangle": 0,
    "arrow-parens": 0,
  },
  "parserOptions": {
    "ecmaVersion": 6,
    "ecmaFeatures": {
      "globalReturn": true,
      "jsx": false,
      "experimentalObjectRestSpread": false
    },
    "sourceType": "script"
  }
}
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/

Statements: 47.84% (232 / 485)      Branches: 23.67% (40 / 169)      Functions: 39.22% (20 / 51)      Lines: 49.46% (230 / 465)      Ignored: 6 statements, 1 function, 1 branch     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/
File Statements Branches Functions Lines
ask.js 26.32% (5 / 19) 0% (0 / 6) 0% (0 / 2) 27.78% (5 / 18)
bin.js 33.8% (48 / 142) 23.21% (13 / 56) 0% (0 / 17) 36.64% (48 / 131)
chrome-finder.js 67.53% (52 / 77) 50% (10 / 20) 71.43% (5 / 7) 68% (51 / 75)
chrome-launcher.js 64.52% (80 / 124) 29.27% (12 / 41) 73.33% (11 / 15) 65.57% (80 / 122)
compiled-check.js 50% (4 / 8) 50% (1 / 2) 100% (1 / 1) 50% (4 / 8)
manual-chrome-launcher.js 69.23% (9 / 13) 50% (1 / 2) 100% (0 / 0) 81.82% (9 / 11)
printer.js 33.33% (30 / 90) 7.14% (3 / 42) 37.5% (3 / 8) 32.58% (29 / 89)
random-port.js 33.33% (4 / 12) 100% (0 / 0) 0% (0 / 1) 36.36% (4 / 11)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/ask.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/ask.js

Statements: 26.32% (5 / 19)      Branches: 0% (0 / 6)      Functions: 0% (0 / 2)      Lines: 27.78% (5 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44                                  1 1 1                                   1 1          
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
const readline = require('readline');
function ask(question, options) {
    return new Promise((resolve, reject) => {
        const iface = readline.createInterface(process.stdin, process.stdout);
        const optionsStr = options.map((o, i) => i + 1 + '. ' + o).join('\r\n');
        iface.setPrompt(question + '\r\n' + optionsStr + '\r\nChoice: ');
        iface.prompt();
        iface.on('line', (_answer) => {
            const answer = toInt(_answer);
            if (answer > 0 && answer <= options.length) {
                iface.close();
                resolve(options[answer - 1]);
            }
            else {
                iface.prompt();
            }
        });
    });
}
exports.ask = ask;
function toInt(n) {
    const result = parseInt(n, 10);
    return isNaN(result) ? 0 : result;
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXNrLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiYXNrLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7Ozs7Ozs7Ozs7R0FlRztBQUVILFlBQVksQ0FBQzs7QUFFYixNQUFNLFFBQVEsR0FBRyxPQUFPLENBQUMsVUFBVSxDQUFDLENBQUM7QUFFckMsYUFBYSxRQUFnQixFQUFFLE9BQWlCO0lBQzlDLE1BQU0sQ0FBQyxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxNQUFNO1FBQ2pDLE1BQU0sS0FBSyxHQUFHLFFBQVEsQ0FBQyxlQUFlLENBQUMsT0FBTyxDQUFDLEtBQUssRUFBRSxPQUFPLENBQUMsTUFBTSxDQUFDLENBQUM7UUFDdEUsTUFBTSxVQUFVLEdBQUcsT0FBTyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsRUFBRSxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsR0FBRyxJQUFJLEdBQUcsQ0FBQyxDQUFDLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDO1FBRXhFLEtBQUssQ0FBQyxTQUFTLENBQUMsUUFBUSxHQUFHLE1BQU0sR0FBRyxVQUFVLEdBQUcsY0FBYyxDQUFDLENBQUM7UUFDakUsS0FBSyxDQUFDLE1BQU0sRUFBRSxDQUFDO1FBRWYsS0FBSyxDQUFDLEVBQUUsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxPQUFlO1lBQy9CLE1BQU0sTUFBTSxHQUFHLEtBQUssQ0FBQyxPQUFPLENBQUMsQ0FBQztZQUM5QixFQUFFLENBQUMsQ0FBQyxNQUFNLEdBQUcsQ0FBQyxJQUFJLE1BQU0sSUFBSSxPQUFPLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQztnQkFDM0MsS0FBSyxDQUFDLEtBQUssRUFBRSxDQUFDO2dCQUNkLE9BQU8sQ0FBQyxPQUFPLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQyxDQUFDLENBQUM7WUFDL0IsQ0FBQztZQUFDLElBQUksQ0FBQyxDQUFDO2dCQUNOLEtBQUssQ0FBQyxNQUFNLEVBQUUsQ0FBQztZQUNqQixDQUFDO1FBQ0gsQ0FBQyxDQUFDLENBQUM7SUFDTCxDQUFDLENBQUMsQ0FBQztBQUNMLENBQUM7QUFPTyxrQkFBRztBQUxYLGVBQWUsQ0FBUztJQUN0QixNQUFNLE1BQU0sR0FBRyxRQUFRLENBQUMsQ0FBQyxFQUFFLEVBQUUsQ0FBQyxDQUFDO0lBQy9CLE1BQU0sQ0FBQyxLQUFLLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQztBQUNwQyxDQUFDIn0=
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/bin.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/bin.js

Statements: 33.8% (48 / 142)      Branches: 23.21% (13 / 56)      Functions: 0% (0 / 17)      Lines: 36.64% (48 / 131)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303                                  1   1 1 1       1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1                                                                                                                                                                 1 1           1       1     1 1 1         1       1 1     1     1       1                                   1                                           1           1             1       1       1                           1                                                                       1                                             1 1     1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const _SIGINT = 'SIGINT';
const _SIGINT_EXIT_CODE = 130;
const _RUNTIME_ERROR_CODE = 1;
const _PROTOCOL_TIMEOUT_EXIT_CODE = 67;
const assetSaver = require('../lighthouse-core/lib/asset-saver.js');
const getFilenamePrefix = require('../lighthouse-core/lib/file-namer.js').getFilenamePrefix;
const chrome_launcher_1 = require("./chrome-launcher");
const Commands = require("./commands/commands");
const lighthouse = require('../lighthouse-core');
const log = require('../lighthouse-core/lib/log');
const Driver = require('../lighthouse-core/gather/driver.js');
const path = require("path");
const perfOnlyConfig = require('../lighthouse-core/config/perf.json');
const performanceXServer = require('./performance-experiment/server');
const Printer = require("./printer");
const randomPort = require("./random-port");
const yargs = require('yargs');
const opn = require('opn');
;
const cliFlags = yargs
    .help('help')
    .version(() => require('../package').version)
    .showHelpOnFail(false, 'Specify --help for available options')
    .usage('$0 url')
    .group([
    'verbose',
    'quiet'
], 'Logging:')
    .describe({
    verbose: 'Displays verbose logging',
    quiet: 'Displays no progress, debug logs or errors'
})
    .group([
    'save-assets',
    'save-artifacts',
    'list-all-audits',
    'list-trace-categories',
    'config-path',
    'chrome-flags',
    'perf',
    'port',
    'max-wait-for-load'
], 'Configuration:')
    .describe({
    'disable-storage-reset': 'Disable clearing the browser cache and other storage APIs before a run',
    'disable-device-emulation': 'Disable Nexus 5X emulation',
    'disable-cpu-throttling': 'Disable CPU throttling',
    'disable-network-throttling': 'Disable network throttling',
    'save-assets': 'Save the trace contents & screenshots to disk',
    'save-artifacts': 'Save all gathered artifacts to disk',
    'list-all-audits': 'Prints a list of all available audits and exits',
    'list-trace-categories': 'Prints a list of all required trace categories and exits',
    'config-path': 'The path to the config JSON.',
    'chrome-flags': 'Custom flags to pass to Chrome.',
    'perf': 'Use a performance-test-only configuration',
    'port': 'The port to use for the debugging protocol. Use 0 for a random port',
    'max-wait-for-load': 'The timeout (in milliseconds) to wait before the page is considered done loading and the run should continue. WARNING: Very high values can lead to large traces and instability',
    'skip-autolaunch': 'Skip autolaunch of Chrome when already running instance is not found',
    'select-chrome': 'Interactively choose version of Chrome to use when multiple installations are found',
    'interactive': 'Open Lighthouse in interactive mode'
})
    .group([
    'output',
    'output-path',
    'view'
], 'Output:')
    .describe({
    'output': 'Reporter for the results, supports multiple values',
    'output-path': `The file path to output the results
Example: --output-path=./lighthouse-results.html`,
    'view': 'Open HTML report in your browser'
})
    .boolean([
    'disable-storage-reset',
    'disable-device-emulation',
    'disable-cpu-throttling',
    'disable-network-throttling',
    'save-assets',
    'save-artifacts',
    'list-all-audits',
    'list-trace-categories',
    'perf',
    'view',
    'skip-autolaunch',
    'select-chrome',
    'verbose',
    'quiet',
    'help',
    'interactive'
])
    .choices('output', Printer.GetValidOutputOptions())
    .default('chrome-flags', '')
    .default('disable-cpu-throttling', true)
    .default('output', Printer.GetValidOutputOptions()[Printer.OutputMode.none])
    .default('output-path', 'stdout')
    .default('port', 9222)
    .default('max-wait-for-load', Driver.MAX_WAIT_FOR_FULLY_LOADED)
    .check((argv) => {
    // Make sure lighthouse has been passed a url, or at least one of --list-all-audits
    // or --list-trace-categories. If not, stop the program and ask for a url
    Eif (!argv.listAllAudits && !argv.listTraceCategories && argv._.length === 0) {
        throw new Error('Please provide a url');
    }
    return true;
})
    .argv;
// Process terminating command
Iif (cliFlags.listAllAudits) {
    Commands.ListAudits();
}
// Process terminating command
Iif (cliFlags.listTraceCategories) {
    Commands.ListTraceCategories();
}
const url = cliFlags._[0];
let config = null;
Iif (cliFlags.configPath) {
    // Resolve the config file path relative to where cli was called.
    cliFlags.configPath = path.resolve(process.cwd(), cliFlags.configPath);
    config = require(cliFlags.configPath);
}
else Iif (cliFlags.perf) {
    config = perfOnlyConfig;
}
// set logging preferences
cliFlags.logLevel = 'info';
Iif (cliFlags.verbose) {
    cliFlags.logLevel = 'verbose';
}
else Iif (cliFlags.quiet) {
    cliFlags.logLevel = 'silent';
}
log.setLevel(cliFlags.logLevel);
/**
 * If the requested port is 0, set it to a random, unused port.
 */
function initPort(flags) {
    return Promise.resolve().then(() => {
        if (flags.port !== 0) {
            log.verbose('Lighthouse CLI', `Using supplied port ${flags.port}`);
            return;
        }
        log.verbose('Lighthouse CLI', 'Generating random port.');
        return randomPort.getRandomPort().then(portNumber => {
            flags.port = portNumber;
            log.verbose('Lighthouse CLI', `Using generated port ${flags.port}.`);
        });
    });
}
/**
 * Attempts to connect to an instance of Chrome with an open remote-debugging
 * port. If none is found and the `skipAutolaunch` flag is not true, launches
 * a debuggable instance.
 */
function getDebuggableChrome(flags) {
    const chromeLauncher = new chrome_launcher_1.ChromeLauncher({
        port: flags.port,
        additionalFlags: flags.chromeFlags.split(' '),
        autoSelectChrome: !flags.selectChrome,
    });
    // Kill spawned Chrome process in case of ctrl-C.
    process.on(_SIGINT, () => {
        chromeLauncher.kill().then(() => process.exit(_SIGINT_EXIT_CODE), handleError);
    });
    return chromeLauncher
        .isDebuggerReady()
        .catch(() => {
        if (flags.skipAutolaunch) {
            return;
        }
        // If not, create one.
        log.log('Lighthouse CLI', 'Launching Chrome...');
        return chromeLauncher.run();
    })
        .then(() => chromeLauncher);
}
function showConnectionError() {
    console.error('Unable to connect to Chrome');
    console.error('If you\'re using lighthouse with --skip-autolaunch, ' +
        'make sure you\'re running some other Chrome with a debugger.');
    process.exit(_RUNTIME_ERROR_CODE);
}
function showRuntimeError(err) {
    console.error('Runtime error encountered:', err);
    if (err.stack) {
        console.error(err.stack);
    }
    process.exit(_RUNTIME_ERROR_CODE);
}
function showProtocolTimeoutError() {
    console.error('Debugger protocol timed out while connecting to Chrome.');
    process.exit(_PROTOCOL_TIMEOUT_EXIT_CODE);
}
function showPageLoadError() {
    console.error('Unable to load the page. Please verify the url you are trying to review.');
    process.exit(_RUNTIME_ERROR_CODE);
}
function handleError(err) {
    if (err.code === 'PAGE_LOAD_ERROR') {
        showPageLoadError();
    }
    else if (err.code === 'ECONNREFUSED') {
        showConnectionError();
    }
    else if (err.code === 'CRI_TIMEOUT') {
        showProtocolTimeoutError();
    }
    else {
        showRuntimeError(err);
    }
}
function saveResults(results, artifacts, flags) {
    let promise = Promise.resolve(results);
    const cwd = process.cwd();
    // Use the output path as the prefix for all generated files.
    // If no output path is set, generate a file prefix using the URL and date.
    const configuredPath = !flags.outputPath || flags.outputPath === 'stdout' ?
        getFilenamePrefix(results) : flags.outputPath.replace(/\.\w{2,4}$/, '');
    const resolvedPath = path.resolve(cwd, configuredPath);
    if (flags.saveArtifacts) {
        assetSaver.saveArtifacts(artifacts, resolvedPath);
    }
    if (flags.saveAssets) {
        promise = promise.then(_ => assetSaver.saveAssets(artifacts, results.audits, resolvedPath));
    }
    if (flags.output === Printer.OutputMode[Printer.OutputMode.none]) {
        promise = promise
            .then(_ => Printer.write(results, 'html', `${resolvedPath}.report.html`))
            .then(_ => {
            if (flags.view)
                return opn(`${resolvedPath}.report.html`, { wait: false });
            log.warn('CLI', 'Report output no longer defaults to stdout. Use `--output=pretty` to re-enable.');
            log.log('CLI', 'Protip: Run lighthouse with `--view` to immediately open the HTML report in your browser');
        });
    }
    return promise.then(_ => {
        if (Array.isArray(flags.output)) {
            return flags.output.reduce((innerPromise, outputType) => {
                const outputPath = `${resolvedPath}.report.${outputType}`;
                return innerPromise.then((_) => Printer.write(results, outputType, outputPath));
            }, Promise.resolve(results));
        }
        else {
            return Printer.write(results, flags.output, flags.outputPath);
        }
    });
}
function runLighthouse(url, flags, config) {
    return __awaiter(this, void 0, void 0, function* () {
        let chromeLauncher = undefined;
        try {
            yield initPort(flags);
            const chromeLauncher = yield getDebuggableChrome(flags);
            const results = yield lighthouse(url, flags, config);
            const artifacts = results.artifacts;
            delete results.artifacts;
            yield saveResults(results, artifacts, flags);
            if (flags.interactive) {
                yield performanceXServer.hostExperiment({ url, flags, config }, results);
            }
            return yield chromeLauncher.kill();
        }
        catch (err) {
            if (typeof chromeLauncher !== 'undefined') {
                yield chromeLauncher.kill();
            }
            return handleError(err);
        }
    });
}
exports.runLighthouse = runLighthouse;
function run() {
    return runLighthouse(url, cliFlags, config);
}
exports.run = run;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmluLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiYmluLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7Ozs7Ozs7Ozs7R0FlRztBQUNILFlBQVksQ0FBQzs7Ozs7Ozs7OztBQUViLE1BQU0sT0FBTyxHQUFHLFFBQVEsQ0FBQztBQUN6QixNQUFNLGlCQUFpQixHQUFHLEdBQUcsQ0FBQztBQUM5QixNQUFNLG1CQUFtQixHQUFHLENBQUMsQ0FBQztBQUM5QixNQUFNLDJCQUEyQixHQUFHLEVBQUUsQ0FBQztBQUV2QyxNQUFNLFVBQVUsR0FBRyxPQUFPLENBQUMsdUNBQXVDLENBQUMsQ0FBQztBQUNwRSxNQUFNLGlCQUFpQixHQUFHLE9BQU8sQ0FBQyxzQ0FBc0MsQ0FBQyxDQUFDLGlCQUFpQixDQUFDO0FBQzVGLHVEQUFpRDtBQUNqRCxnREFBZ0Q7QUFDaEQsTUFBTSxVQUFVLEdBQUcsT0FBTyxDQUFDLG9CQUFvQixDQUFDLENBQUM7QUFDakQsTUFBTSxHQUFHLEdBQUcsT0FBTyxDQUFDLDRCQUE0QixDQUFDLENBQUM7QUFDbEQsTUFBTSxNQUFNLEdBQUcsT0FBTyxDQUFDLHFDQUFxQyxDQUFDLENBQUM7QUFDOUQsNkJBQTZCO0FBQzdCLE1BQU0sY0FBYyxHQUFHLE9BQU8sQ0FBQyxxQ0FBcUMsQ0FBQyxDQUFDO0FBQ3RFLE1BQU0sa0JBQWtCLEdBQUcsT0FBTyxDQUFDLGlDQUFpQyxDQUFDLENBQUM7QUFDdEUscUNBQXFDO0FBQ3JDLDRDQUE0QztBQUU1QyxNQUFNLEtBQUssR0FBRyxPQUFPLENBQUMsT0FBTyxDQUFDLENBQUM7QUFDL0IsTUFBTSxHQUFHLEdBQUcsT0FBTyxDQUFDLEtBQUssQ0FBQyxDQUFDO0FBSTFCLENBQUM7QUFFRixNQUFNLFFBQVEsR0FBRyxLQUFLO0tBQ25CLElBQUksQ0FBQyxNQUFNLENBQUM7S0FDWixPQUFPLENBQUMsTUFBTSxPQUFPLENBQUMsWUFBWSxDQUFDLENBQUMsT0FBTyxDQUFDO0tBQzVDLGNBQWMsQ0FBQyxLQUFLLEVBQUUsc0NBQXNDLENBQUM7S0FFN0QsS0FBSyxDQUFDLFFBQVEsQ0FBQztLQUdmLEtBQUssQ0FBQztJQUNMLFNBQVM7SUFDVCxPQUFPO0NBQ1IsRUFBRSxVQUFVLENBQUM7S0FDYixRQUFRLENBQUM7SUFDUixPQUFPLEVBQUUsMEJBQTBCO0lBQ25DLEtBQUssRUFBRSw0Q0FBNEM7Q0FDcEQsQ0FBQztLQUVELEtBQUssQ0FBQztJQUNMLGFBQWE7SUFDYixnQkFBZ0I7SUFDaEIsaUJBQWlCO0lBQ2pCLHVCQUF1QjtJQUN2QixhQUFhO0lBQ2IsY0FBYztJQUNkLE1BQU07SUFDTixNQUFNO0lBQ04sbUJBQW1CO0NBQ3BCLEVBQUUsZ0JBQWdCLENBQUM7S0FDbkIsUUFBUSxDQUFDO0lBQ1IsdUJBQXVCLEVBQUUsd0VBQXdFO0lBQ2pHLDBCQUEwQixFQUFFLDRCQUE0QjtJQUN4RCx3QkFBd0IsRUFBRSx3QkFBd0I7SUFDbEQsNEJBQTRCLEVBQUUsNEJBQTRCO0lBQzFELGFBQWEsRUFBRSwrQ0FBK0M7SUFDOUQsZ0JBQWdCLEVBQUUscUNBQXFDO0lBQ3ZELGlCQUFpQixFQUFFLGlEQUFpRDtJQUNwRSx1QkFBdUIsRUFBRSwwREFBMEQ7SUFDbkYsYUFBYSxFQUFFLDhCQUE4QjtJQUM3QyxjQUFjLEVBQUUsaUNBQWlDO0lBQ2pELE1BQU0sRUFBRSwyQ0FBMkM7SUFDbkQsTUFBTSxFQUFFLHFFQUFxRTtJQUM3RSxtQkFBbUIsRUFBRSxrTEFBa0w7SUFDdk0saUJBQWlCLEVBQUUsc0VBQXNFO0lBQ3pGLGVBQWUsRUFBRSxxRkFBcUY7SUFDdEcsYUFBYSxFQUFFLHFDQUFxQztDQUNyRCxDQUFDO0tBRUQsS0FBSyxDQUFDO0lBQ0wsUUFBUTtJQUNSLGFBQWE7SUFDYixNQUFNO0NBQ1AsRUFBRSxTQUFTLENBQUM7S0FDWixRQUFRLENBQUM7SUFDUixRQUFRLEVBQUUsb0RBQW9EO0lBQzlELGFBQWEsRUFBRTtpREFDOEI7SUFDN0MsTUFBTSxFQUFFLGtDQUFrQztDQUMzQyxDQUFDO0tBR0QsT0FBTyxDQUFDO0lBQ1AsdUJBQXVCO0lBQ3ZCLDBCQUEwQjtJQUMxQix3QkFBd0I7SUFDeEIsNEJBQTRCO0lBQzVCLGFBQWE7SUFDYixnQkFBZ0I7SUFDaEIsaUJBQWlCO0lBQ2pCLHVCQUF1QjtJQUN2QixNQUFNO0lBQ04sTUFBTTtJQUNOLGlCQUFpQjtJQUNqQixlQUFlO0lBQ2YsU0FBUztJQUNULE9BQU87SUFDUCxNQUFNO0lBQ04sYUFBYTtDQUNkLENBQUM7S0FDRCxPQUFPLENBQUMsUUFBUSxFQUFFLE9BQU8sQ0FBQyxxQkFBcUIsRUFBRSxDQUFDO0tBR2xELE9BQU8sQ0FBQyxjQUFjLEVBQUUsRUFBRSxDQUFDO0tBQzNCLE9BQU8sQ0FBQyx3QkFBd0IsRUFBRSxJQUFJLENBQUM7S0FDdkMsT0FBTyxDQUFDLFFBQVEsRUFBRSxPQUFPLENBQUMscUJBQXFCLEVBQUUsQ0FBQyxPQUFPLENBQUMsVUFBVSxDQUFDLElBQUksQ0FBQyxDQUFDO0tBQzNFLE9BQU8sQ0FBQyxhQUFhLEVBQUUsUUFBUSxDQUFDO0tBQ2hDLE9BQU8sQ0FBQyxNQUFNLEVBQUUsSUFBSSxDQUFDO0tBQ3JCLE9BQU8sQ0FBQyxtQkFBbUIsRUFBRSxNQUFNLENBQUMseUJBQXlCLENBQUM7S0FDOUQsS0FBSyxDQUFDLENBQUMsSUFBNkU7SUFDbkYsbUZBQW1GO0lBQ25GLHlFQUF5RTtJQUN6RSxFQUFFLENBQUMsQ0FBQyxDQUFDLElBQUksQ0FBQyxhQUFhLElBQUksQ0FBQyxJQUFJLENBQUMsbUJBQW1CLElBQUksSUFBSSxDQUFDLENBQUMsQ0FBQyxNQUFNLEtBQUssQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUM1RSxNQUFNLElBQUksS0FBSyxDQUFDLHNCQUFzQixDQUFDLENBQUM7SUFDMUMsQ0FBQztJQUVELE1BQU0sQ0FBQyxJQUFJLENBQUM7QUFDZCxDQUFDLENBQUM7S0FDRCxJQUFJLENBQUM7QUFFUiw4QkFBOEI7QUFDOUIsRUFBRSxDQUFDLENBQUMsUUFBUSxDQUFDLGFBQWEsQ0FBQyxDQUFDLENBQUM7SUFDM0IsUUFBUSxDQUFDLFVBQVUsRUFBRSxDQUFDO0FBQ3hCLENBQUM7QUFFRCw4QkFBOEI7QUFDOUIsRUFBRSxDQUFDLENBQUMsUUFBUSxDQUFDLG1CQUFtQixDQUFDLENBQUMsQ0FBQztJQUNqQyxRQUFRLENBQUMsbUJBQW1CLEVBQUUsQ0FBQztBQUNqQyxDQUFDO0FBRUQsTUFBTSxHQUFHLEdBQUcsUUFBUSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztBQUUxQixJQUFJLE1BQU0sR0FBa0IsSUFBSSxDQUFDO0FBQ2pDLEVBQUUsQ0FBQyxDQUFDLFFBQVEsQ0FBQyxVQUFVLENBQUMsQ0FBQyxDQUFDO0lBQ3hCLGlFQUFpRTtJQUNqRSxRQUFRLENBQUMsVUFBVSxHQUFHLElBQUksQ0FBQyxPQUFPLENBQUMsT0FBTyxDQUFDLEdBQUcsRUFBRSxFQUFFLFFBQVEsQ0FBQyxVQUFVLENBQUMsQ0FBQztJQUN2RSxNQUFNLEdBQUcsT0FBTyxDQUFDLFFBQVEsQ0FBQyxVQUFVLENBQUMsQ0FBQztBQUN4QyxDQUFDO0FBQUMsSUFBSSxDQUFDLEVBQUUsQ0FBQyxDQUFDLFFBQVEsQ0FBQyxJQUFJLENBQUMsQ0FBQyxDQUFDO0lBQ3pCLE1BQU0sR0FBRyxjQUFjLENBQUM7QUFDMUIsQ0FBQztBQUVELDBCQUEwQjtBQUMxQixRQUFRLENBQUMsUUFBUSxHQUFHLE1BQU0sQ0FBQztBQUMzQixFQUFFLENBQUMsQ0FBQyxRQUFRLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQztJQUNyQixRQUFRLENBQUMsUUFBUSxHQUFHLFNBQVMsQ0FBQztBQUNoQyxDQUFDO0FBQUMsSUFBSSxDQUFDLEVBQUUsQ0FBQyxDQUFDLFFBQVEsQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDO0lBQzFCLFFBQVEsQ0FBQyxRQUFRLEdBQUcsUUFBUSxDQUFDO0FBQy9CLENBQUM7QUFDRCxHQUFHLENBQUMsUUFBUSxDQUFDLFFBQVEsQ0FBQyxRQUFRLENBQUMsQ0FBQztBQUVoQzs7R0FFRztBQUNILGtCQUFrQixLQUFxQjtJQUNyQyxNQUFNLENBQUMsT0FBTyxDQUFDLE9BQU8sRUFBRSxDQUFDLElBQUksQ0FBQztRQUM1QixFQUFFLENBQUMsQ0FBQyxLQUFLLENBQUMsSUFBSSxLQUFLLENBQUMsQ0FBQyxDQUFDLENBQUM7WUFDckIsR0FBRyxDQUFDLE9BQU8sQ0FBQyxnQkFBZ0IsRUFBRSx1QkFBdUIsS0FBSyxDQUFDLElBQUksRUFBRSxDQUFDLENBQUM7WUFDbkUsTUFBTSxDQUFDO1FBQ1QsQ0FBQztRQUVELEdBQUcsQ0FBQyxPQUFPLENBQUMsZ0JBQWdCLEVBQUUseUJBQXlCLENBQUMsQ0FBQztRQUN6RCxNQUFNLENBQUMsVUFBVSxDQUFDLGFBQWEsRUFBRSxDQUFDLElBQUksQ0FBQyxVQUFVO1lBQy9DLEtBQUssQ0FBQyxJQUFJLEdBQUcsVUFBVSxDQUFDO1lBQ3hCLEdBQUcsQ0FBQyxPQUFPLENBQUMsZ0JBQWdCLEVBQUUsd0JBQXdCLEtBQUssQ0FBQyxJQUFJLEdBQUcsQ0FBQyxDQUFDO1FBQ3ZFLENBQUMsQ0FBQyxDQUFDO0lBQ0wsQ0FBQyxDQUFDLENBQUE7QUFDSixDQUFDO0FBRUQ7Ozs7R0FJRztBQUNILDZCQUE2QixLQUNzQjtJQUNqRCxNQUFNLGNBQWMsR0FBRyxJQUFJLGdDQUFjLENBQUM7UUFDeEMsSUFBSSxFQUFFLEtBQUssQ0FBQyxJQUFJO1FBQ2hCLGVBQWUsRUFBRSxLQUFLLENBQUMsV0FBVyxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUM7UUFDN0MsZ0JBQWdCLEVBQUUsQ0FBQyxLQUFLLENBQUMsWUFBWTtLQUN0QyxDQUFDLENBQUM7SUFFSCxpREFBaUQ7SUFDakQsT0FBTyxDQUFDLEVBQUUsQ0FBQyxPQUFPLEVBQUU7UUFDbEIsY0FBYyxDQUFDLElBQUksRUFBRSxDQUFDLElBQUksQ0FBQyxNQUFNLE9BQU8sQ0FBQyxJQUFJLENBQUMsaUJBQWlCLENBQUMsRUFBRSxXQUFXLENBQUMsQ0FBQztJQUNqRixDQUFDLENBQUMsQ0FBQztJQUVILE1BQU0sQ0FBQyxjQUFjO1NBRWxCLGVBQWUsRUFBRTtTQUNqQixLQUFLLENBQUM7UUFDTCxFQUFFLENBQUMsQ0FBQyxLQUFLLENBQUMsY0FBYyxDQUFDLENBQUMsQ0FBQztZQUN6QixNQUFNLENBQUM7UUFDVCxDQUFDO1FBRUQsc0JBQXNCO1FBQ3RCLEdBQUcsQ0FBQyxHQUFHLENBQUMsZ0JBQWdCLEVBQUUscUJBQXFCLENBQUMsQ0FBQztRQUNqRCxNQUFNLENBQUMsY0FBYyxDQUFDLEdBQUcsRUFBRSxDQUFDO0lBQzlCLENBQUMsQ0FBQztTQUNELElBQUksQ0FBQyxNQUFNLGNBQWMsQ0FBQyxDQUFDO0FBQ2hDLENBQUM7QUFFRDtJQUNFLE9BQU8sQ0FBQyxLQUFLLENBQUMsNkJBQTZCLENBQUMsQ0FBQztJQUM3QyxPQUFPLENBQUMsS0FBSyxDQUNYLHNEQUFzRDtRQUN0RCw4REFBOEQsQ0FDL0QsQ0FBQztJQUNGLE9BQU8sQ0FBQyxJQUFJLENBQUMsbUJBQW1CLENBQUMsQ0FBQztBQUNwQyxDQUFDO0FBRUQsMEJBQTBCLEdBQW9CO0lBQzVDLE9BQU8sQ0FBQyxLQUFLLENBQUMsNEJBQTRCLEVBQUUsR0FBRyxDQUFDLENBQUM7SUFDakQsRUFBRSxDQUFDLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxDQUFDLENBQUM7UUFDZCxPQUFPLENBQUMsS0FBSyxDQUFDLEdBQUcsQ0FBQyxLQUFLLENBQUMsQ0FBQztJQUMzQixDQUFDO0lBQ0QsT0FBTyxDQUFDLElBQUksQ0FBQyxtQkFBbUIsQ0FBQyxDQUFDO0FBQ3BDLENBQUM7QUFFRDtJQUNFLE9BQU8sQ0FBQyxLQUFLLENBQUMseURBQXlELENBQUMsQ0FBQztJQUN6RSxPQUFPLENBQUMsSUFBSSxDQUFDLDJCQUEyQixDQUFDLENBQUM7QUFDNUMsQ0FBQztBQUVEO0lBQ0UsT0FBTyxDQUFDLEtBQUssQ0FBQywwRUFBMEUsQ0FBQyxDQUFDO0lBQzFGLE9BQU8sQ0FBQyxJQUFJLENBQUMsbUJBQW1CLENBQUMsQ0FBQztBQUNwQyxDQUFDO0FBRUQscUJBQXFCLEdBQW9CO0lBQ3ZDLEVBQUUsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxJQUFJLEtBQUssaUJBQWlCLENBQUMsQ0FBQyxDQUFDO1FBQ25DLGlCQUFpQixFQUFFLENBQUM7SUFDdEIsQ0FBQztJQUFDLElBQUksQ0FBQyxFQUFFLENBQUMsQ0FBQyxHQUFHLENBQUMsSUFBSSxLQUFLLGNBQWMsQ0FBQyxDQUFDLENBQUM7UUFDdkMsbUJBQW1CLEVBQUUsQ0FBQztJQUN4QixDQUFDO0lBQUMsSUFBSSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxJQUFJLEtBQUssYUFBYSxDQUFDLENBQUMsQ0FBQztRQUN0Qyx3QkFBd0IsRUFBRSxDQUFDO0lBQzdCLENBQUM7SUFBQyxJQUFJLENBQUMsQ0FBQztRQUNOLGdCQUFnQixDQUFDLEdBQUcsQ0FBQyxDQUFDO0lBQ3hCLENBQUM7QUFDSCxDQUFDO0FBRUQscUJBQXFCLE9BQWdCLEVBQ2hCLFNBQWlCLEVBQ2pCLEtBQW9HO0lBQ3JILElBQUksT0FBTyxHQUFHLE9BQU8sQ0FBQyxPQUFPLENBQUMsT0FBTyxDQUFDLENBQUM7SUFDdkMsTUFBTSxHQUFHLEdBQUcsT0FBTyxDQUFDLEdBQUcsRUFBRSxDQUFDO0lBQzFCLDZEQUE2RDtJQUM3RCwyRUFBMkU7SUFDM0UsTUFBTSxjQUFjLEdBQUcsQ0FBQyxLQUFLLENBQUMsVUFBVSxJQUFJLEtBQUssQ0FBQyxVQUFVLEtBQUssUUFBUTtRQUNyRSxpQkFBaUIsQ0FBQyxPQUFPLENBQUMsR0FBRyxLQUFLLENBQUMsVUFBVSxDQUFDLE9BQU8sQ0FBQyxZQUFZLEVBQUUsRUFBRSxDQUFDLENBQUM7SUFDNUUsTUFBTSxZQUFZLEdBQUcsSUFBSSxDQUFDLE9BQU8sQ0FBQyxHQUFHLEVBQUUsY0FBYyxDQUFDLENBQUM7SUFFdkQsRUFBRSxDQUFDLENBQUMsS0FBSyxDQUFDLGFBQWEsQ0FBQyxDQUFDLENBQUM7UUFDeEIsVUFBVSxDQUFDLGFBQWEsQ0FBQyxTQUFTLEVBQUUsWUFBWSxDQUFDLENBQUM7SUFDcEQsQ0FBQztJQUVELEVBQUUsQ0FBQyxDQUFDLEtBQUssQ0FBQyxVQUFVLENBQUMsQ0FBQyxDQUFDO1FBQ3JCLE9BQU8sR0FBRyxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUMsSUFBSSxVQUFVLENBQUMsVUFBVSxDQUFDLFNBQVMsRUFBRSxPQUFPLENBQUMsTUFBTSxFQUFFLFlBQVksQ0FBQyxDQUFDLENBQUM7SUFDOUYsQ0FBQztJQUVELEVBQUUsQ0FBQyxDQUFDLEtBQUssQ0FBQyxNQUFNLEtBQUssT0FBTyxDQUFDLFVBQVUsQ0FBQyxPQUFPLENBQUMsVUFBVSxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUNqRSxPQUFPLEdBQUcsT0FBTzthQUNaLElBQUksQ0FBQyxDQUFDLElBQUksT0FBTyxDQUFDLEtBQUssQ0FBQyxPQUFPLEVBQUUsTUFBTSxFQUFFLEdBQUcsWUFBWSxjQUFjLENBQUMsQ0FBQzthQUN4RSxJQUFJLENBQUMsQ0FBQztZQUNMLEVBQUUsQ0FBQyxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUM7Z0JBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLFlBQVksY0FBYyxFQUFFLEVBQUMsSUFBSSxFQUFFLEtBQUssRUFBQyxDQUFDLENBQUM7WUFFekUsR0FBRyxDQUFDLElBQUksQ0FBQyxLQUFLLEVBQUUsaUZBQWlGLENBQUMsQ0FBQztZQUNuRyxHQUFHLENBQUMsR0FBRyxDQUFDLEtBQUssRUFBRSwwRkFBMEYsQ0FBQyxDQUFDO1FBQzdHLENBQUMsQ0FBQyxDQUFDO0lBQ1QsQ0FBQztJQUVELE1BQU0sQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDbkIsRUFBRSxDQUFDLENBQUMsS0FBSyxDQUFDLE9BQU8sQ0FBQyxLQUFLLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDO1lBQ2hDLE1BQU0sQ0FBQyxLQUFLLENBQUMsTUFBTSxDQUFDLE1BQU0sQ0FBQyxDQUFDLFlBQVksRUFBRSxVQUFVO2dCQUNsRCxNQUFNLFVBQVUsR0FBRyxHQUFHLFlBQVksV0FBVyxVQUFVLEVBQUUsQ0FBQztnQkFDMUQsTUFBTSxDQUFDLFlBQVksQ0FBQyxJQUFJLENBQUMsQ0FBQyxDQUFVLEtBQUssT0FBTyxDQUFDLEtBQUssQ0FBQyxPQUFPLEVBQUUsVUFBVSxFQUFFLFVBQVUsQ0FBQyxDQUFDLENBQUM7WUFDM0YsQ0FBQyxFQUFFLE9BQU8sQ0FBQyxPQUFPLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQztRQUMvQixDQUFDO1FBQUMsSUFBSSxDQUFDLENBQUM7WUFDTixNQUFNLENBQUMsT0FBTyxDQUFDLEtBQUssQ0FBQyxPQUFPLEVBQUUsS0FBSyxDQUFDLE1BQU0sRUFBRSxLQUFLLENBQUMsVUFBVSxDQUFDLENBQUM7UUFDaEUsQ0FBQztJQUNILENBQUMsQ0FBQyxDQUFDO0FBQ1AsQ0FBQztBQUVELHVCQUFvQyxHQUFXLEVBQ3hCLEtBRTZELEVBQzdELE1BQXFCOztRQUUxQyxJQUFJLGNBQWMsR0FBK0IsU0FBUyxDQUFDO1FBRTNELElBQUksQ0FBQztZQUNILE1BQU0sUUFBUSxDQUFDLEtBQUssQ0FBQyxDQUFBO1lBQ3JCLE1BQU0sY0FBYyxHQUFHLE1BQU0sbUJBQW1CLENBQUMsS0FBSyxDQUFDLENBQUE7WUFDdkQsTUFBTSxPQUFPLEdBQUcsTUFBTSxVQUFVLENBQUMsR0FBRyxFQUFFLEtBQUssRUFBRSxNQUFNLENBQUMsQ0FBQztZQUVyRCxNQUFNLFNBQVMsR0FBRyxPQUFPLENBQUMsU0FBUyxDQUFDO1lBQ3BDLE9BQU8sT0FBTyxDQUFDLFNBQVMsQ0FBQztZQUV6QixNQUFNLFdBQVcsQ0FBQyxPQUFPLEVBQUUsU0FBVSxFQUFFLEtBQUssQ0FBQyxDQUFDO1lBQzlDLEVBQUUsQ0FBQyxDQUFDLEtBQUssQ0FBQyxXQUFXLENBQUMsQ0FBQyxDQUFDO2dCQUN0QixNQUFNLGtCQUFrQixDQUFDLGNBQWMsQ0FBQyxFQUFDLEdBQUcsRUFBRSxLQUFLLEVBQUUsTUFBTSxFQUFDLEVBQUUsT0FBTyxDQUFDLENBQUM7WUFDekUsQ0FBQztZQUVELE1BQU0sQ0FBQyxNQUFNLGNBQWMsQ0FBQyxJQUFJLEVBQUUsQ0FBQztRQUNyQyxDQUFDO1FBQUMsS0FBSyxDQUFDLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQztZQUNiLEVBQUUsQ0FBQyxDQUFDLE9BQU8sY0FBYyxLQUFLLFdBQVcsQ0FBQyxDQUFDLENBQUM7Z0JBQzFDLE1BQU0sY0FBZSxDQUFDLElBQUksRUFBRSxDQUFDO1lBQy9CLENBQUM7WUFFRCxNQUFNLENBQUMsV0FBVyxDQUFDLEdBQUcsQ0FBQyxDQUFDO1FBQzFCLENBQUM7SUFDRixDQUFDO0NBQUE7QUE3QkYsc0NBNkJFO0FBRUY7SUFDRSxNQUFNLENBQUMsYUFBYSxDQUFDLEdBQUcsRUFBRSxRQUFRLEVBQUUsTUFBTSxDQUFDLENBQUM7QUFDOUMsQ0FBQztBQUZELGtCQUVDIn0=
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/chrome-finder.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/chrome-finder.js

Statements: 67.53% (52 / 77)      Branches: 50% (10 / 20)      Functions: 71.43% (5 / 7)      Lines: 68% (51 / 75)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194                                  1 1 1 1 1 1 1                                                                                   1             1 1   1       1       1 2     1       1 2 2     2 2             1       1                         1   1 1                                           1 1 1 1   2 5 2         1 2   1 10 3   7 7 7           1 1   1 2 2 2 2       2     5 5   2      
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require('fs');
const path = require('path');
const execSync = require('child_process').execSync;
const execFileSync = require('child_process').execFileSync;
const newLineRegex = /\r?\n/;
function darwin() {
    const suffixes = [
        '/Contents/MacOS/Google Chrome Canary',
        '/Contents/MacOS/Google Chrome'
    ];
    const LSREGISTER = '/System/Library/Frameworks/CoreServices.framework' +
        '/Versions/A/Frameworks/LaunchServices.framework' +
        '/Versions/A/Support/lsregister';
    const installations = [];
    execSync(`${LSREGISTER} -dump` +
        ' | grep -i \'google chrome\\( canary\\)\\?.app$\'' +
        ' | awk \'{$1=""; print $0}\'').toString()
        .split(newLineRegex)
        .forEach((inst) => {
        suffixes.forEach(suffix => {
            const execPath = path.join(inst.trim(), suffix);
            if (canAccess(execPath)) {
                installations.push(execPath);
            }
        });
    });
    const priorities = [{
            regex: new RegExp(`^${process.env.HOME}/Applications/.*Chrome.app`),
            weight: 50
        }, {
            regex: new RegExp(`^${process.env.HOME}/Applications/.*Chrome Canary.app`),
            weight: 51
        }, {
            regex: /^\/Applications\/.*Chrome.app/,
            weight: 100
        }, {
            regex: /^\/Applications\/.*Chrome Canary.app/,
            weight: 101
        }, {
            regex: /^\/Volumes\/.*Chrome.app/,
            weight: -2
        }, {
            regex: /^\/Volumes\/.*Chrome Canary.app/,
            weight: -1
        }];
    return sort(installations, priorities);
}
exports.darwin = darwin;
/**
 * Look for linux executables in 3 ways
 * 1. Look into LIGHTHOUSE_CHROMIUM_PATH env variable
 * 2. Look into the directories where .desktop are saved on gnome based distro's
 * 3. Look for google-chrome-stable & google-chrome executables by using the which command
 */
function linux() {
    let installations = [];
    // 1. Look into LIGHTHOUSE_CHROMIUM_PATH env variable
    Iif (canAccess(process.env.LIGHTHOUSE_CHROMIUM_PATH)) {
        installations.push(process.env.LIGHTHOUSE_CHROMIUM_PATH);
    }
    // 2. Look into the directories where .desktop are saved on gnome based distro's
    const desktopInstallationFolders = [
        path.join(require('os').homedir(), '.local/share/applications/'),
        '/usr/share/applications/',
    ];
    desktopInstallationFolders.forEach(folder => {
        installations = installations.concat(findChromeExecutables(folder));
    });
    // Look for google-chrome-stable & google-chrome executables by using the which command
    const executables = [
        'google-chrome-stable',
        'google-chrome',
    ];
    executables.forEach((executable) => {
        try {
            const chromePath = execFileSync('which', [executable])
                .toString()
                .split(newLineRegex)[0];
            Eif (canAccess(chromePath)) {
                installations.push(chromePath);
            }
        }
        catch (e) {
            // Not installed.
        }
    });
    Iif (!installations.length) {
        throw new Error('The environment variable LIGHTHOUSE_CHROMIUM_PATH must be set to ' +
            'executable of a build of Chromium version 54.0 or later.');
    }
    const priorities = [{
            regex: /chrome-wrapper$/,
            weight: 51
        }, {
            regex: /google-chrome-stable$/,
            weight: 50
        }, {
            regex: /google-chrome$/,
            weight: 49
        }, {
            regex: new RegExp(process.env.LIGHTHOUSE_CHROMIUM_PATH),
            weight: 100
        }];
    return sort(uniq(installations.filter(Boolean)), priorities);
}
exports.linux = linux;
function win32() {
    const installations = [];
    const suffixes = [
        '\\Google\\Chrome SxS\\Application\\chrome.exe',
        '\\Google\\Chrome\\Application\\chrome.exe'
    ];
    const prefixes = [
        process.env.LOCALAPPDATA,
        process.env.PROGRAMFILES,
        process.env['PROGRAMFILES(X86)']
    ];
    if (canAccess(process.env.LIGHTHOUSE_CHROMIUM_PATH)) {
        installations.push(process.env.LIGHTHOUSE_CHROMIUM_PATH);
    }
    prefixes.forEach(prefix => suffixes.forEach(suffix => {
        const chromePath = path.join(prefix, suffix);
        if (canAccess(chromePath)) {
            installations.push(chromePath);
        }
    }));
    return installations;
}
exports.win32 = win32;
function sort(installations, priorities) {
    const defaultPriority = 10;
    return installations
        .map((inst) => {
        for (const pair of priorities) {
            if (pair.regex.test(inst)) {
                return [inst, pair.weight];
            }
        }
        return [inst, defaultPriority];
    })
        .sort((a, b) => b[1] - a[1])
        .map(pair => pair[0]);
}
function canAccess(file) {
    if (!file) {
        return false;
    }
    try {
        fs.accessSync(file);
        return true;
    }
    catch (e) {
        return false;
    }
}
function uniq(arr) {
    return Array.from(new Set(arr));
}
function findChromeExecutables(folder) {
    const argumentsRegex = /(^[^ ]+).*/; // Take everything up to the first space
    const chromeExecRegex = '^Exec=\/.*\/(google|chrome|chromium)-.*';
    let installations = [];
    Eif (canAccess(folder)) {
        // Output of the grep & print looks like:
        //    /opt/google/chrome/google-chrome --profile-directory
        //    /home/user/Downloads/chrome-linux/chrome-wrapper %U
        let execPaths = execSync(`grep -ER "${chromeExecRegex}" ${folder} | awk -F '=' '{print $2}'`)
            .toString()
            .split(newLineRegex)
            .map((execPath) => execPath.replace(argumentsRegex, '$1'));
        execPaths.forEach((execPath) => canAccess(execPath) && installations.push(execPath));
    }
    return installations;
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2hyb21lLWZpbmRlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImNocm9tZS1maW5kZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7Ozs7Ozs7Ozs7OztHQWVHO0FBRUgsWUFBWSxDQUFDOztBQUViLE1BQU0sRUFBRSxHQUFHLE9BQU8sQ0FBQyxJQUFJLENBQUMsQ0FBQztBQUN6QixNQUFNLElBQUksR0FBRyxPQUFPLENBQUMsTUFBTSxDQUFDLENBQUM7QUFDN0IsTUFBTSxRQUFRLEdBQUcsT0FBTyxDQUFDLGVBQWUsQ0FBQyxDQUFDLFFBQVEsQ0FBQztBQUNuRCxNQUFNLFlBQVksR0FBRyxPQUFPLENBQUMsZUFBZSxDQUFDLENBQUMsWUFBWSxDQUFDO0FBRTNELE1BQU0sWUFBWSxHQUFHLE9BQU8sQ0FBQztBQUk3QjtJQUNFLE1BQU0sUUFBUSxHQUFHO1FBQ2Ysc0NBQXNDO1FBQ3RDLCtCQUErQjtLQUNoQyxDQUFDO0lBRUYsTUFBTSxVQUFVLEdBQ2QsbURBQW1EO1FBQ25ELGlEQUFpRDtRQUNqRCxnQ0FBZ0MsQ0FBQztJQUVuQyxNQUFNLGFBQWEsR0FBa0IsRUFBRSxDQUFDO0lBRXhDLFFBQVEsQ0FDTixHQUFHLFVBQVUsUUFBUTtRQUNyQixtREFBbUQ7UUFDbkQsOEJBQThCLENBQy9CLENBQUMsUUFBUSxFQUFFO1NBQ1QsS0FBSyxDQUFDLFlBQVksQ0FBQztTQUNuQixPQUFPLENBQUMsQ0FBQyxJQUFZO1FBQ3BCLFFBQVEsQ0FBQyxPQUFPLENBQUMsTUFBTTtZQUNyQixNQUFNLFFBQVEsR0FBRyxJQUFJLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxJQUFJLEVBQUUsRUFBRSxNQUFNLENBQUMsQ0FBQztZQUNoRCxFQUFFLENBQUMsQ0FBQyxTQUFTLENBQUMsUUFBUSxDQUFDLENBQUMsQ0FBQyxDQUFDO2dCQUN4QixhQUFhLENBQUMsSUFBSSxDQUFDLFFBQVEsQ0FBQyxDQUFDO1lBQy9CLENBQUM7UUFDSCxDQUFDLENBQUMsQ0FBQztJQUNMLENBQUMsQ0FBQyxDQUFDO0lBRUwsTUFBTSxVQUFVLEdBQWUsQ0FBQztZQUM5QixLQUFLLEVBQUUsSUFBSSxNQUFNLENBQUMsSUFBSSxPQUFPLENBQUMsR0FBRyxDQUFDLElBQUksNEJBQTRCLENBQUM7WUFDbkUsTUFBTSxFQUFFLEVBQUU7U0FDWCxFQUFFO1lBQ0QsS0FBSyxFQUFFLElBQUksTUFBTSxDQUFDLElBQUksT0FBTyxDQUFDLEdBQUcsQ0FBQyxJQUFJLG1DQUFtQyxDQUFDO1lBQzFFLE1BQU0sRUFBRSxFQUFFO1NBQ1gsRUFBRTtZQUNELEtBQUssRUFBRSwrQkFBK0I7WUFDdEMsTUFBTSxFQUFFLEdBQUc7U0FDWixFQUFFO1lBQ0QsS0FBSyxFQUFFLHNDQUFzQztZQUM3QyxNQUFNLEVBQUUsR0FBRztTQUNaLEVBQUU7WUFDRCxLQUFLLEVBQUUsMEJBQTBCO1lBQ2pDLE1BQU0sRUFBRSxDQUFDLENBQUM7U0FDWCxFQUFFO1lBQ0QsS0FBSyxFQUFFLGlDQUFpQztZQUN4QyxNQUFNLEVBQUUsQ0FBQyxDQUFDO1NBQ1gsQ0FBQyxDQUFDO0lBRUgsTUFBTSxDQUFDLElBQUksQ0FBQyxhQUFhLEVBQUUsVUFBVSxDQUFDLENBQUM7QUFDekMsQ0FBQztBQWpERCx3QkFpREM7QUFFRDs7Ozs7R0FLRztBQUNIO0lBQ0UsSUFBSSxhQUFhLEdBQWtCLEVBQUUsQ0FBQztJQUV0QyxxREFBcUQ7SUFDckQsRUFBRSxDQUFDLENBQUMsU0FBUyxDQUFDLE9BQU8sQ0FBQyxHQUFHLENBQUMsd0JBQXdCLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFDcEQsYUFBYSxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLHdCQUF3QixDQUFDLENBQUM7SUFDM0QsQ0FBQztJQUVELGdGQUFnRjtJQUNoRixNQUFNLDBCQUEwQixHQUFHO1FBQ2pDLElBQUksQ0FBQyxJQUFJLENBQUMsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDLE9BQU8sRUFBRSxFQUFFLDRCQUE0QixDQUFDO1FBQ2hFLDBCQUEwQjtLQUMzQixDQUFDO0lBQ0YsMEJBQTBCLENBQUMsT0FBTyxDQUFDLE1BQU07UUFDdkMsYUFBYSxHQUFHLGFBQWEsQ0FBQyxNQUFNLENBQUMscUJBQXFCLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQztJQUN0RSxDQUFDLENBQUMsQ0FBQztJQUVILHVGQUF1RjtJQUN2RixNQUFNLFdBQVcsR0FBRztRQUNsQixzQkFBc0I7UUFDdEIsZUFBZTtLQUNoQixDQUFDO0lBQ0YsV0FBVyxDQUFDLE9BQU8sQ0FBQyxDQUFDLFVBQWtCO1FBQ3JDLElBQUksQ0FBQztZQUNILE1BQU0sVUFBVSxHQUFHLFlBQVksQ0FBQyxPQUFPLEVBQUUsQ0FBQyxVQUFVLENBQUMsQ0FBQztpQkFDbkQsUUFBUSxFQUFFO2lCQUNWLEtBQUssQ0FBQyxZQUFZLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztZQUUxQixFQUFFLENBQUMsQ0FBQyxTQUFTLENBQUMsVUFBVSxDQUFDLENBQUMsQ0FBQyxDQUFDO2dCQUMxQixhQUFhLENBQUMsSUFBSSxDQUFDLFVBQVUsQ0FBQyxDQUFDO1lBQ2pDLENBQUM7UUFDSCxDQUFDO1FBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztZQUNYLGlCQUFpQjtRQUNuQixDQUFDO0lBQ0gsQ0FBQyxDQUFDLENBQUM7SUFFSCxFQUFFLENBQUMsQ0FBQyxDQUFDLGFBQWEsQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDO1FBQzFCLE1BQU0sSUFBSSxLQUFLLENBQUMsbUVBQW1FO1lBQ2pGLDBEQUEwRCxDQUFDLENBQUM7SUFDaEUsQ0FBQztJQUVELE1BQU0sVUFBVSxHQUFlLENBQUM7WUFDOUIsS0FBSyxFQUFFLGlCQUFpQjtZQUN4QixNQUFNLEVBQUUsRUFBRTtTQUNYLEVBQUU7WUFDRCxLQUFLLEVBQUUsdUJBQXVCO1lBQzlCLE1BQU0sRUFBRSxFQUFFO1NBQ1gsRUFBRTtZQUNELEtBQUssRUFBRSxnQkFBZ0I7WUFDdkIsTUFBTSxFQUFFLEVBQUU7U0FDWCxFQUFFO1lBQ0QsS0FBSyxFQUFFLElBQUksTUFBTSxDQUFDLE9BQU8sQ0FBQyxHQUFHLENBQUMsd0JBQXdCLENBQUM7WUFDdkQsTUFBTSxFQUFFLEdBQUc7U0FDWixDQUFDLENBQUM7SUFFSCxNQUFNLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxhQUFhLENBQUMsTUFBTSxDQUFDLE9BQU8sQ0FBQyxDQUFDLEVBQUUsVUFBVSxDQUFDLENBQUM7QUFDL0QsQ0FBQztBQXhERCxzQkF3REM7QUFFRDtJQUNFLE1BQU0sYUFBYSxHQUFrQixFQUFFLENBQUM7SUFDeEMsTUFBTSxRQUFRLEdBQUc7UUFDZiwrQ0FBK0M7UUFDL0MsMkNBQTJDO0tBQzVDLENBQUM7SUFDRixNQUFNLFFBQVEsR0FBRztRQUNmLE9BQU8sQ0FBQyxHQUFHLENBQUMsWUFBWTtRQUN4QixPQUFPLENBQUMsR0FBRyxDQUFDLFlBQVk7UUFDeEIsT0FBTyxDQUFDLEdBQUcsQ0FBQyxtQkFBbUIsQ0FBQztLQUNqQyxDQUFDO0lBRUYsRUFBRSxDQUFDLENBQUMsU0FBUyxDQUFDLE9BQU8sQ0FBQyxHQUFHLENBQUMsd0JBQXdCLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFDcEQsYUFBYSxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLHdCQUF3QixDQUFDLENBQUM7SUFDM0QsQ0FBQztJQUVELFFBQVEsQ0FBQyxPQUFPLENBQUMsTUFBTSxJQUNyQixRQUFRLENBQUMsT0FBTyxDQUFDLE1BQU07UUFDckIsTUFBTSxVQUFVLEdBQUcsSUFBSSxDQUFDLElBQUksQ0FBQyxNQUFNLEVBQUUsTUFBTSxDQUFDLENBQUM7UUFDN0MsRUFBRSxDQUFDLENBQUMsU0FBUyxDQUFDLFVBQVUsQ0FBQyxDQUFDLENBQUMsQ0FBQztZQUMxQixhQUFhLENBQUMsSUFBSSxDQUFDLFVBQVUsQ0FBQyxDQUFDO1FBQ2pDLENBQUM7SUFDSCxDQUFDLENBQUMsQ0FDSCxDQUFDO0lBQ0YsTUFBTSxDQUFDLGFBQWEsQ0FBQztBQUN2QixDQUFDO0FBekJELHNCQXlCQztBQUVELGNBQWMsYUFBNEIsRUFBRSxVQUFzQjtJQUNoRSxNQUFNLGVBQWUsR0FBRyxFQUFFLENBQUM7SUFDM0IsTUFBTSxDQUFDLGFBQWE7U0FFakIsR0FBRyxDQUFDLENBQUMsSUFBWTtRQUNoQixHQUFHLENBQUMsQ0FBQyxNQUFNLElBQUksSUFBSSxVQUFVLENBQUMsQ0FBQyxDQUFDO1lBQzlCLEVBQUUsQ0FBQyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQztnQkFDMUIsTUFBTSxDQUFDLENBQUMsSUFBSSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQztZQUM3QixDQUFDO1FBQ0gsQ0FBQztRQUNELE1BQU0sQ0FBQyxDQUFDLElBQUksRUFBRSxlQUFlLENBQUMsQ0FBQztJQUNqQyxDQUFDLENBQUM7U0FFRCxJQUFJLENBQUMsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxLQUFXLENBQUUsQ0FBQyxDQUFDLENBQUMsR0FBUyxDQUFFLENBQUMsQ0FBQyxDQUFDLENBQUM7U0FFekMsR0FBRyxDQUFDLElBQUksSUFBSSxJQUFJLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztBQUMxQixDQUFDO0FBRUQsbUJBQW1CLElBQVk7SUFDN0IsRUFBRSxDQUFDLENBQUMsQ0FBQyxJQUFJLENBQUMsQ0FBQyxDQUFDO1FBQ1YsTUFBTSxDQUFDLEtBQUssQ0FBQztJQUNmLENBQUM7SUFFRCxJQUFJLENBQUM7UUFDSCxFQUFFLENBQUMsVUFBVSxDQUFDLElBQUksQ0FBQyxDQUFDO1FBQ3BCLE1BQU0sQ0FBQyxJQUFJLENBQUM7SUFDZCxDQUFDO0lBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUNYLE1BQU0sQ0FBQyxLQUFLLENBQUM7SUFDZixDQUFDO0FBQ0gsQ0FBQztBQUVELGNBQWMsR0FBZTtJQUN6QixNQUFNLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxJQUFJLEdBQUcsQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDO0FBQ3BDLENBQUM7QUFFRCwrQkFBK0IsTUFBYztJQUMzQyxNQUFNLGNBQWMsR0FBRyxZQUFZLENBQUMsQ0FBQyx3Q0FBd0M7SUFDN0UsTUFBTSxlQUFlLEdBQUcseUNBQXlDLENBQUM7SUFFbEUsSUFBSSxhQUFhLEdBQWtCLEVBQUUsQ0FBQztJQUN0QyxFQUFFLENBQUMsQ0FBQyxTQUFTLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDO1FBQ3RCLHlDQUF5QztRQUN6QywwREFBMEQ7UUFDMUQseURBQXlEO1FBQ3pELElBQUksU0FBUyxHQUFHLFFBQVEsQ0FBQyxhQUFhLGVBQWUsS0FBSyxNQUFNLDRCQUE0QixDQUFDO2FBQzFGLFFBQVEsRUFBRTthQUNWLEtBQUssQ0FBQyxZQUFZLENBQUM7YUFDbkIsR0FBRyxDQUFDLENBQUMsUUFBZ0IsS0FBSyxRQUFRLENBQUMsT0FBTyxDQUFDLGNBQWMsRUFBRSxJQUFJLENBQUMsQ0FBQyxDQUFDO1FBRXJFLFNBQVMsQ0FBQyxPQUFPLENBQUMsQ0FBQyxRQUFnQixLQUFLLFNBQVMsQ0FBQyxRQUFRLENBQUMsSUFBSSxhQUFhLENBQUMsSUFBSSxDQUFDLFFBQVEsQ0FBQyxDQUFDLENBQUM7SUFDL0YsQ0FBQztJQUVELE1BQU0sQ0FBQyxhQUFhLENBQUM7QUFDdkIsQ0FBQyJ9
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/chrome-launcher.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/chrome-launcher.js

Statements: 64.52% (80 / 124)      Branches: 29.27% (12 / 41)      Functions: 73.33% (11 / 15)      Lines: 65.57% (80 / 122)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243                                  1 1 1 1 1 1 1 1 1 1 1 1 1       1 1 1   1 1 1 1     1                                           1 1   1 1 1     1     1 1             1 1     1 1 1     1     1   1 1     1 1       1     1 1       1       1 1 1 1   1     1 1 1 1 1         1 1 1       1 1 1           1 1 1 1 1 1 1   1 1 1 1     1 1                                                                                                               1   1 4   1     1 1   1                    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
const childProcess = require("child_process");
const fs = require("fs");
const path = require("path");
const chromeFinder = require("./chrome-finder");
const ask_1 = require("./ask");
const mkdirp = require('mkdirp');
const net = require("net");
const rimraf = require('rimraf');
const log = require('../lighthouse-core/lib/log');
const spawn = childProcess.spawn;
const execSync = childProcess.execSync;
const isWindows = process.platform === 'win32';
class ChromeLauncher {
    // We can not use default args here due to support node pre 6.
    constructor(opts) {
        this.prepared = false;
        this.pollInterval = 500;
        opts = opts || {};
        // choose the first one (default)
        this.autoSelectChrome = defaults(opts.autoSelectChrome, true);
        this.startingUrl = defaults(opts.startingUrl, 'about:blank');
        this.additionalFlags = defaults(opts.additionalFlags, []);
        this.port = defaults(opts.port, 9222);
    }
    flags() {
        const flags = [
            `--remote-debugging-port=${this.port}`,
            // Disable built-in Google Translate service
            '--disable-translate',
            // Disable all chrome extensions entirely
            '--disable-extensions',
            // Disable various background network services, including extension updating,
            //   safe browsing service, upgrade detector, translate, UMA
            '--disable-background-networking',
            // Disable fetching safebrowsing lists, likely redundant due to disable-background-networking
            '--safebrowsing-disable-auto-update',
            // Disable syncing to a Google account
            '--disable-sync',
            // Disable reporting to UMA, but allows for collection
            '--metrics-recording-only',
            // Disable installation of default apps on first run
            '--disable-default-apps',
            // Skip first run wizards
            '--no-first-run',
            // Place Chrome profile in a custom location we'll rm -rf later
            `--user-data-dir=${this.TMP_PROFILE_DIR}`
        ];
        Eif (process.platform === 'linux') {
            flags.push('--disable-setuid-sandbox');
        }
        flags.push(...this.additionalFlags);
        flags.push(this.startingUrl);
        return flags;
    }
    prepare() {
        switch (process.platform) {
            case 'darwin':
            case 'linux':
                this.TMP_PROFILE_DIR = unixTmpDir();
                break;
            case 'win32':
                this.TMP_PROFILE_DIR = win32TmpDir();
                break;
            default:
                throw new Error('Platform ' + process.platform + ' is not supported');
        }
        this.outFile = fs.openSync(`${this.TMP_PROFILE_DIR}/chrome-out.log`, 'a');
        this.errFile = fs.openSync(`${this.TMP_PROFILE_DIR}/chrome-err.log`, 'a');
        // fix for Node4
        // you can't pass a fd to fs.writeFileSync
        this.pidFile = `${this.TMP_PROFILE_DIR}/chrome.pid`;
        log.verbose('ChromeLauncher', `created ${this.TMP_PROFILE_DIR}`);
        this.prepared = true;
    }
    run() {
        Iif (!this.prepared) {
            this.prepare();
        }
        return Promise.resolve()
            .then(() => {
            const installations = chromeFinder[process.platform]();
            Iif (installations.length < 1) {
                return Promise.reject(new Error('No Chrome Installations Found'));
            }
            else Eif (installations.length === 1 || this.autoSelectChrome) {
                return installations[0];
            }
            return ask_1.ask('Choose a Chrome installation to use with Lighthouse', installations);
        })
            .then(execPath => this.spawn(execPath));
    }
    spawn(execPath) {
        return new Promise((resolve, reject) => {
            Iif (this.chrome) {
                log.log('ChromeLauncher', `Chrome already running with pid ${this.chrome.pid}.`);
                return resolve(this.chrome.pid);
            }
            const chrome = spawn(execPath, this.flags(), {
                detached: true,
                stdio: ['ignore', this.outFile, this.errFile]
            });
            this.chrome = chrome;
            fs.writeFileSync(this.pidFile, chrome.pid.toString());
            log.verbose('ChromeLauncher', `Chrome running with pid ${chrome.pid} on port ${this.port}.`);
            resolve(chrome.pid);
        })
            .then(pid => Promise.all([pid, this.waitUntilReady()]));
    }
    cleanup(client) {
        Eif (client) {
            client.removeAllListeners();
            client.end();
            client.destroy();
            client.unref();
        }
    }
    // resolves if ready, rejects otherwise
    isDebuggerReady() {
        return new Promise((resolve, reject) => {
            const client = net.createConnection(this.port);
            client.once('error', err => {
                this.cleanup(client);
                reject(err);
            });
            client.once('connect', () => {
                this.cleanup(client);
                resolve();
            });
        });
    }
    // resolves when debugger is ready, rejects after 10 polls
    waitUntilReady() {
        const launcher = this;
        return new Promise((resolve, reject) => {
            let retries = 0;
            let waitStatus = 'Waiting for browser.';
            (function poll() {
                Eif (retries === 0) {
                    log.log('ChromeLauncher', waitStatus);
                }
                retries++;
                waitStatus += '..';
                log.log('ChromeLauncher', waitStatus);
                launcher
                    .isDebuggerReady()
                    .then(() => {
                    log.log('ChromeLauncher', waitStatus + `${log.greenify(log.tick)}`);
                    resolve();
                })
                    .catch(err => {
                    if (retries > 10) {
                        return reject(err);
                    }
                    delay(launcher.pollInterval).then(poll);
                });
            })();
        });
    }
    kill() {
        return new Promise(resolve => {
            if (this.chrome) {
                this.chrome.on('close', () => {
                    this.destroyTmp()
                        .then(resolve);
                });
                log.log('ChromeLauncher', 'Killing all Chrome Instances');
                try {
                    if (isWindows) {
                        execSync(`taskkill /pid ${this.chrome.pid} /T /F`);
                    }
                    else {
                        process.kill(-this.chrome.pid);
                    }
                }
                catch (err) {
                    log.warn('ChromeLauncher', `Chrome could not be killed ${err.message}`);
                }
                delete this.chrome;
            }
            else {
                // fail silently as we did not start chrome
                resolve();
            }
        });
    }
    destroyTmp() {
        return new Promise(resolve => {
            if (!this.TMP_PROFILE_DIR) {
                return resolve();
            }
            log.verbose('ChromeLauncher', `Removing ${this.TMP_PROFILE_DIR}`);
            if (this.outFile) {
                fs.closeSync(this.outFile);
                delete this.outFile;
            }
            if (this.errFile) {
                fs.closeSync(this.errFile);
                delete this.errFile;
            }
            rimraf(this.TMP_PROFILE_DIR, () => resolve());
        });
    }
}
exports.ChromeLauncher = ChromeLauncher;
;
function defaults(val, def) {
    return typeof val === 'undefined' ? def : val;
}
function delay(time) {
    return new Promise(resolve => setTimeout(resolve, time));
}
function unixTmpDir() {
    return execSync('mktemp -d -t lighthouse.XXXXXXX').toString().trim();
}
function win32TmpDir() {
    const winTmpPath = process.env.TEMP ||
        process.env.TMP ||
        (process.env.SystemRoot || process.env.windir) + '\\temp';
    const randomNumber = Math.floor(Math.random() * 9e7 + 1e7);
    const tmpdir = path.join(winTmpPath, 'lighthouse.' + randomNumber);
    mkdirp.sync(tmpdir);
    return tmpdir;
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2hyb21lLWxhdW5jaGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiY2hyb21lLWxhdW5jaGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7Ozs7Ozs7Ozs7R0FlRztBQUVILFlBQVksQ0FBQzs7QUFFYiw4Q0FBOEM7QUFDOUMseUJBQXlCO0FBQ3pCLDZCQUE2QjtBQUM3QixnREFBZ0Q7QUFDaEQsK0JBQTBCO0FBRTFCLE1BQU0sTUFBTSxHQUFHLE9BQU8sQ0FBQyxRQUFRLENBQUMsQ0FBQztBQUNqQywyQkFBMkI7QUFDM0IsTUFBTSxNQUFNLEdBQUcsT0FBTyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0FBQ2pDLE1BQU0sR0FBRyxHQUFHLE9BQU8sQ0FBQyw0QkFBNEIsQ0FBQyxDQUFDO0FBQ2xELE1BQU0sS0FBSyxHQUFHLFlBQVksQ0FBQyxLQUFLLENBQUM7QUFDakMsTUFBTSxRQUFRLEdBQUcsWUFBWSxDQUFDLFFBQVEsQ0FBQztBQUN2QyxNQUFNLFNBQVMsR0FBRyxPQUFPLENBQUMsUUFBUSxLQUFLLE9BQU8sQ0FBQztBQUUvQztJQWFFLDhEQUE4RDtJQUM5RCxZQUFZLElBSU07UUFqQmxCLGFBQVEsR0FBWSxLQUFLLENBQUE7UUFDekIsaUJBQVksR0FBVyxHQUFHLENBQUE7UUFrQnBCLElBQUksR0FBRyxJQUFJLElBQUksRUFBRSxDQUFDO1FBRWxCLGlDQUFpQztRQUNqQyxJQUFJLENBQUMsZ0JBQWdCLEdBQUcsUUFBUSxDQUFDLElBQUksQ0FBQyxnQkFBZ0IsRUFBRSxJQUFJLENBQUMsQ0FBQztRQUM5RCxJQUFJLENBQUMsV0FBVyxHQUFHLFFBQVEsQ0FBQyxJQUFJLENBQUMsV0FBVyxFQUFFLGFBQWEsQ0FBQyxDQUFDO1FBQzdELElBQUksQ0FBQyxlQUFlLEdBQUcsUUFBUSxDQUFDLElBQUksQ0FBQyxlQUFlLEVBQUUsRUFBRSxDQUFDLENBQUM7UUFDMUQsSUFBSSxDQUFDLElBQUksR0FBRyxRQUFRLENBQUMsSUFBSSxDQUFDLElBQUksRUFBRSxJQUFJLENBQUMsQ0FBQztJQUM1QyxDQUFDO0lBRUQsS0FBSztRQUNILE1BQU0sS0FBSyxHQUFHO1lBQ1osMkJBQTJCLElBQUksQ0FBQyxJQUFJLEVBQUU7WUFDdEMsNENBQTRDO1lBQzVDLHFCQUFxQjtZQUNyQix5Q0FBeUM7WUFDekMsc0JBQXNCO1lBQ3RCLDZFQUE2RTtZQUM3RSw0REFBNEQ7WUFDNUQsaUNBQWlDO1lBQ2pDLDZGQUE2RjtZQUM3RixvQ0FBb0M7WUFDcEMsc0NBQXNDO1lBQ3RDLGdCQUFnQjtZQUNoQixzREFBc0Q7WUFDdEQsMEJBQTBCO1lBQzFCLG9EQUFvRDtZQUNwRCx3QkFBd0I7WUFDeEIseUJBQXlCO1lBQ3pCLGdCQUFnQjtZQUNoQiwrREFBK0Q7WUFDL0QsbUJBQW1CLElBQUksQ0FBQyxlQUFlLEVBQUU7U0FDMUMsQ0FBQztRQUVGLEVBQUUsQ0FBQyxDQUFDLE9BQU8sQ0FBQyxRQUFRLEtBQUssT0FBTyxDQUFDLENBQUMsQ0FBQztZQUNqQyxLQUFLLENBQUMsSUFBSSxDQUFDLDBCQUEwQixDQUFDLENBQUM7UUFDekMsQ0FBQztRQUVELEtBQUssQ0FBQyxJQUFJLENBQUMsR0FBRyxJQUFJLENBQUMsZUFBZSxDQUFDLENBQUM7UUFDcEMsS0FBSyxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsV0FBVyxDQUFDLENBQUM7UUFFN0IsTUFBTSxDQUFDLEtBQUssQ0FBQztJQUNmLENBQUM7SUFFRCxPQUFPO1FBQ0wsTUFBTSxDQUFDLENBQUMsT0FBTyxDQUFDLFFBQVEsQ0FBQyxDQUFDLENBQUM7WUFDekIsS0FBSyxRQUFRLENBQUM7WUFDZCxLQUFLLE9BQU87Z0JBQ1YsSUFBSSxDQUFDLGVBQWUsR0FBRyxVQUFVLEVBQUUsQ0FBQztnQkFDcEMsS0FBSyxDQUFDO1lBRVIsS0FBSyxPQUFPO2dCQUNWLElBQUksQ0FBQyxlQUFlLEdBQUcsV0FBVyxFQUFFLENBQUM7Z0JBQ3JDLEtBQUssQ0FBQztZQUVSO2dCQUNFLE1BQU0sSUFBSSxLQUFLLENBQUMsV0FBVyxHQUFHLE9BQU8sQ0FBQyxRQUFRLEdBQUcsbUJBQW1CLENBQUMsQ0FBQztRQUMxRSxDQUFDO1FBRUQsSUFBSSxDQUFDLE9BQU8sR0FBRyxFQUFFLENBQUMsUUFBUSxDQUFDLEdBQUcsSUFBSSxDQUFDLGVBQWUsaUJBQWlCLEVBQUUsR0FBRyxDQUFDLENBQUM7UUFDMUUsSUFBSSxDQUFDLE9BQU8sR0FBRyxFQUFFLENBQUMsUUFBUSxDQUFDLEdBQUcsSUFBSSxDQUFDLGVBQWUsaUJBQWlCLEVBQUUsR0FBRyxDQUFDLENBQUM7UUFFMUUsZ0JBQWdCO1FBQ2hCLDBDQUEwQztRQUMxQyxJQUFJLENBQUMsT0FBTyxHQUFHLEdBQUcsSUFBSSxDQUFDLGVBQWUsYUFBYSxDQUFDO1FBRXBELEdBQUcsQ0FBQyxPQUFPLENBQUMsZ0JBQWdCLEVBQUUsV0FBVyxJQUFJLENBQUMsZUFBZSxFQUFFLENBQUMsQ0FBQztRQUVqRSxJQUFJLENBQUMsUUFBUSxHQUFHLElBQUksQ0FBQztJQUN2QixDQUFDO0lBRUQsR0FBRztRQUNELEVBQUUsQ0FBQyxDQUFDLENBQUMsSUFBSSxDQUFDLFFBQVEsQ0FBQyxDQUFDLENBQUM7WUFDbkIsSUFBSSxDQUFDLE9BQU8sRUFBRSxDQUFDO1FBQ2pCLENBQUM7UUFFRCxNQUFNLENBQUMsT0FBTyxDQUFDLE9BQU8sRUFBRTthQUNyQixJQUFJLENBQUM7WUFDSixNQUFNLGFBQWEsR0FBUyxZQUFhLENBQUMsT0FBTyxDQUFDLFFBQVEsQ0FBQyxFQUFFLENBQUM7WUFFOUQsRUFBRSxDQUFDLENBQUMsYUFBYSxDQUFDLE1BQU0sR0FBRyxDQUFDLENBQUMsQ0FBQyxDQUFDO2dCQUM3QixNQUFNLENBQUMsT0FBTyxDQUFDLE1BQU0sQ0FBQyxJQUFJLEtBQUssQ0FBQywrQkFBK0IsQ0FBQyxDQUFDLENBQUM7WUFDcEUsQ0FBQztZQUFDLElBQUksQ0FBQyxFQUFFLENBQUMsQ0FBQyxhQUFhLENBQUMsTUFBTSxLQUFLLENBQUMsSUFBSSxJQUFJLENBQUMsZ0JBQWdCLENBQUMsQ0FBQyxDQUFDO2dCQUMvRCxNQUFNLENBQUMsYUFBYSxDQUFDLENBQUMsQ0FBQyxDQUFDO1lBQzFCLENBQUM7WUFFRCxNQUFNLENBQUMsU0FBRyxDQUFDLHFEQUFxRCxFQUFFLGFBQWEsQ0FBQyxDQUFDO1FBQ25GLENBQUMsQ0FBQzthQUNELElBQUksQ0FBQyxRQUFRLElBQUksSUFBSSxDQUFDLEtBQUssQ0FBQyxRQUFRLENBQUMsQ0FBQyxDQUFDO0lBQzVDLENBQUM7SUFFRCxLQUFLLENBQUMsUUFBZ0I7UUFDcEIsTUFBTSxDQUFDLElBQUksT0FBTyxDQUFDLENBQUMsT0FBTyxFQUFFLE1BQU07WUFDakMsRUFBRSxDQUFDLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUM7Z0JBQ2hCLEdBQUcsQ0FBQyxHQUFHLENBQUMsZ0JBQWdCLEVBQUUsbUNBQW1DLElBQUksQ0FBQyxNQUFNLENBQUMsR0FBRyxHQUFHLENBQUMsQ0FBQztnQkFDakYsTUFBTSxDQUFDLE9BQU8sQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1lBQ2xDLENBQUM7WUFFRCxNQUFNLE1BQU0sR0FBRyxLQUFLLENBQ2xCLFFBQVEsRUFDUixJQUFJLENBQUMsS0FBSyxFQUFFLEVBQ1o7Z0JBQ0UsUUFBUSxFQUFFLElBQUk7Z0JBQ2QsS0FBSyxFQUFFLENBQUMsUUFBUSxFQUFFLElBQUksQ0FBQyxPQUFPLEVBQUUsSUFBSSxDQUFDLE9BQU8sQ0FBQzthQUM5QyxDQUNGLENBQUM7WUFDRixJQUFJLENBQUMsTUFBTSxHQUFHLE1BQU0sQ0FBQztZQUVyQixFQUFFLENBQUMsYUFBYSxDQUFDLElBQUksQ0FBQyxPQUFPLEVBQUUsTUFBTSxDQUFDLEdBQUcsQ0FBQyxRQUFRLEVBQUUsQ0FBQyxDQUFDO1lBRXRELEdBQUcsQ0FBQyxPQUFPLENBQUMsZ0JBQWdCLEVBQUUsMkJBQTJCLE1BQU0sQ0FBQyxHQUFHLFlBQVksSUFBSSxDQUFDLElBQUksR0FBRyxDQUFDLENBQUM7WUFDN0YsT0FBTyxDQUFDLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztRQUN0QixDQUFDLENBQUM7YUFDRCxJQUFJLENBQUMsR0FBRyxJQUFJLE9BQU8sQ0FBQyxHQUFHLENBQUMsQ0FBQyxHQUFHLEVBQUUsSUFBSSxDQUFDLGNBQWMsRUFBRSxDQUFDLENBQUMsQ0FBQyxDQUFDO0lBQzFELENBQUM7SUFFRCxPQUFPLENBQUMsTUFBbUI7UUFDekIsRUFBRSxDQUFDLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQztZQUNYLE1BQU0sQ0FBQyxrQkFBa0IsRUFBRSxDQUFDO1lBQzVCLE1BQU0sQ0FBQyxHQUFHLEVBQUUsQ0FBQztZQUNiLE1BQU0sQ0FBQyxPQUFPLEVBQUUsQ0FBQztZQUNqQixNQUFNLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDakIsQ0FBQztJQUNILENBQUM7SUFFRCx1Q0FBdUM7SUFDdkMsZUFBZTtRQUNiLE1BQU0sQ0FBQyxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxNQUFNO1lBQ2pDLE1BQU0sTUFBTSxHQUFHLEdBQUcsQ0FBQyxnQkFBZ0IsQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7WUFDL0MsTUFBTSxDQUFDLElBQUksQ0FBQyxPQUFPLEVBQUUsR0FBRztnQkFDdEIsSUFBSSxDQUFDLE9BQU8sQ0FBQyxNQUFNLENBQUMsQ0FBQztnQkFDckIsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1lBQ2QsQ0FBQyxDQUFDLENBQUM7WUFDSCxNQUFNLENBQUMsSUFBSSxDQUFDLFNBQVMsRUFBRTtnQkFDckIsSUFBSSxDQUFDLE9BQU8sQ0FBQyxNQUFNLENBQUMsQ0FBQztnQkFDckIsT0FBTyxFQUFFLENBQUM7WUFDWixDQUFDLENBQUMsQ0FBQztRQUNMLENBQUMsQ0FBQyxDQUFDO0lBQ0wsQ0FBQztJQUVELDBEQUEwRDtJQUMxRCxjQUFjO1FBQ1osTUFBTSxRQUFRLEdBQUcsSUFBSSxDQUFDO1FBRXRCLE1BQU0sQ0FBQyxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxNQUFNO1lBQ2pDLElBQUksT0FBTyxHQUFHLENBQUMsQ0FBQztZQUNoQixJQUFJLFVBQVUsR0FBRyxzQkFBc0IsQ0FBQztZQUN4QyxDQUFDO2dCQUNDLEVBQUUsQ0FBQyxDQUFDLE9BQU8sS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFDO29CQUNsQixHQUFHLENBQUMsR0FBRyxDQUFDLGdCQUFnQixFQUFFLFVBQVUsQ0FBQyxDQUFDO2dCQUN4QyxDQUFDO2dCQUNELE9BQU8sRUFBRSxDQUFDO2dCQUNWLFVBQVUsSUFBSSxJQUFJLENBQUM7Z0JBQ25CLEdBQUcsQ0FBQyxHQUFHLENBQUMsZ0JBQWdCLEVBQUUsVUFBVSxDQUFDLENBQUM7Z0JBRXRDLFFBQVE7cUJBQ0wsZUFBZSxFQUFFO3FCQUNqQixJQUFJLENBQUM7b0JBQ0osR0FBRyxDQUFDLEdBQUcsQ0FBQyxnQkFBZ0IsRUFBRSxVQUFVLEdBQUcsR0FBRyxHQUFHLENBQUMsUUFBUSxDQUFDLEdBQUcsQ0FBQyxJQUFJLENBQUMsRUFBRSxDQUFDLENBQUM7b0JBQ3BFLE9BQU8sRUFBRSxDQUFDO2dCQUNaLENBQUMsQ0FBQztxQkFDRCxLQUFLLENBQUMsR0FBRztvQkFDUixFQUFFLENBQUMsQ0FBQyxPQUFPLEdBQUcsRUFBRSxDQUFDLENBQUMsQ0FBQzt3QkFDakIsTUFBTSxDQUFDLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztvQkFDckIsQ0FBQztvQkFDRCxLQUFLLENBQUMsUUFBUSxDQUFDLFlBQVksQ0FBQyxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQztnQkFDMUMsQ0FBQyxDQUFDLENBQUM7WUFDUCxDQUFDLENBQUMsRUFBRSxDQUFDO1FBQ1AsQ0FBQyxDQUFDLENBQUM7SUFDTCxDQUFDO0lBRUQsSUFBSTtRQUNGLE1BQU0sQ0FBQyxJQUFJLE9BQU8sQ0FBQyxPQUFPO1lBQ3hCLEVBQUUsQ0FBQyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDO2dCQUNoQixJQUFJLENBQUMsTUFBTSxDQUFDLEVBQUUsQ0FBQyxPQUFPLEVBQUU7b0JBQ3RCLElBQUksQ0FBQyxVQUFVLEVBQUU7eUJBQ2QsSUFBSSxDQUFDLE9BQU8sQ0FBQyxDQUFDO2dCQUNuQixDQUFDLENBQUMsQ0FBQztnQkFFSCxHQUFHLENBQUMsR0FBRyxDQUFDLGdCQUFnQixFQUFFLDhCQUE4QixDQUFDLENBQUM7Z0JBQzFELElBQUksQ0FBQztvQkFDSCxFQUFFLENBQUMsQ0FBQyxTQUFTLENBQUMsQ0FBQyxDQUFDO3dCQUNkLFFBQVEsQ0FBQyxpQkFBaUIsSUFBSSxDQUFDLE1BQU0sQ0FBQyxHQUFHLFFBQVEsQ0FBQyxDQUFDO29CQUNyRCxDQUFDO29CQUFDLElBQUksQ0FBQyxDQUFDO3dCQUNOLE9BQU8sQ0FBQyxJQUFJLENBQUMsQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDO29CQUNqQyxDQUFDO2dCQUNILENBQUM7Z0JBQUMsS0FBSyxDQUFDLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQztvQkFDYixHQUFHLENBQUMsSUFBSSxDQUFDLGdCQUFnQixFQUFFLDhCQUE4QixHQUFHLENBQUMsT0FBTyxFQUFFLENBQUMsQ0FBQztnQkFDMUUsQ0FBQztnQkFFRCxPQUFPLElBQUksQ0FBQyxNQUFNLENBQUM7WUFDckIsQ0FBQztZQUFDLElBQUksQ0FBQyxDQUFDO2dCQUNOLDJDQUEyQztnQkFDM0MsT0FBTyxFQUFFLENBQUM7WUFDWixDQUFDO1FBQ0gsQ0FBQyxDQUFDLENBQUM7SUFDTCxDQUFDO0lBRUQsVUFBVTtRQUNSLE1BQU0sQ0FBQyxJQUFJLE9BQU8sQ0FBQyxPQUFPO1lBQ3hCLEVBQUUsQ0FBQyxDQUFDLENBQUMsSUFBSSxDQUFDLGVBQWUsQ0FBQyxDQUFDLENBQUM7Z0JBQzFCLE1BQU0sQ0FBQyxPQUFPLEVBQUUsQ0FBQztZQUNuQixDQUFDO1lBRUQsR0FBRyxDQUFDLE9BQU8sQ0FBQyxnQkFBZ0IsRUFBRSxZQUFZLElBQUksQ0FBQyxlQUFlLEVBQUUsQ0FBQyxDQUFDO1lBRWxFLEVBQUUsQ0FBQyxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUMsQ0FBQyxDQUFDO2dCQUNqQixFQUFFLENBQUMsU0FBUyxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUMsQ0FBQztnQkFDM0IsT0FBTyxJQUFJLENBQUMsT0FBTyxDQUFDO1lBQ3RCLENBQUM7WUFFRCxFQUFFLENBQUMsQ0FBQyxJQUFJLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQztnQkFDakIsRUFBRSxDQUFDLFNBQVMsQ0FBQyxJQUFJLENBQUMsT0FBTyxDQUFDLENBQUM7Z0JBQzNCLE9BQU8sSUFBSSxDQUFDLE9BQU8sQ0FBQztZQUN0QixDQUFDO1lBRUQsTUFBTSxDQUFDLElBQUksQ0FBQyxlQUFlLEVBQUUsTUFBTSxPQUFPLEVBQUUsQ0FBQyxDQUFDO1FBQ2hELENBQUMsQ0FBQyxDQUFDO0lBQ0wsQ0FBQztDQUNGO0FBOU9ELHdDQThPQztBQUFBLENBQUM7QUFFRixrQkFBa0IsR0FBUSxFQUFFLEdBQVE7SUFDbEMsTUFBTSxDQUFDLE9BQU8sR0FBRyxLQUFLLFdBQVcsR0FBRyxHQUFHLEdBQUcsR0FBRyxDQUFDO0FBQ2hELENBQUM7QUFFRCxlQUFlLElBQVk7SUFDekIsTUFBTSxDQUFDLElBQUksT0FBTyxDQUFDLE9BQU8sSUFBSSxVQUFVLENBQUMsT0FBTyxFQUFFLElBQUksQ0FBQyxDQUFDLENBQUM7QUFDM0QsQ0FBQztBQUVEO0lBQ0UsTUFBTSxDQUFDLFFBQVEsQ0FBQyxpQ0FBaUMsQ0FBQyxDQUFDLFFBQVEsRUFBRSxDQUFDLElBQUksRUFBRSxDQUFDO0FBQ3ZFLENBQUM7QUFFRDtJQUNFLE1BQU0sVUFBVSxHQUFHLE9BQU8sQ0FBQyxHQUFHLENBQUMsSUFBSTtRQUNqQyxPQUFPLENBQUMsR0FBRyxDQUFDLEdBQUc7UUFDZixDQUFDLE9BQU8sQ0FBQyxHQUFHLENBQUMsVUFBVSxJQUFJLE9BQU8sQ0FBQyxHQUFHLENBQUMsTUFBTSxDQUFDLEdBQUcsUUFBUSxDQUFDO0lBQzVELE1BQU0sWUFBWSxHQUFHLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLE1BQU0sRUFBRSxHQUFHLEdBQUcsR0FBRyxHQUFHLENBQUMsQ0FBQztJQUMzRCxNQUFNLE1BQU0sR0FBRyxJQUFJLENBQUMsSUFBSSxDQUFDLFVBQVUsRUFBRSxhQUFhLEdBQUcsWUFBWSxDQUFDLENBQUM7SUFFbkUsTUFBTSxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQztJQUNwQixNQUFNLENBQUMsTUFBTSxDQUFDO0FBQ2hCLENBQUMifQ==
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/compiled-check.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/compiled-check.js

Statements: 50% (4 / 8)      Branches: 50% (1 / 2)      Functions: 100% (1 / 1)      Lines: 50% (4 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15    1 1   1 1                
'use strict'
 
const fs = require('fs');
const path = require('path');
 
module.exports = function(filename) {
  Iif (!fs.existsSync(path.join(__dirname, filename))) {
    console.log('Oops! Looks like the CLI needs to be compiled. Please run:');
    console.log('   npm run install-cli');
    console.log('More at: https://github.com/GoogleChrome/lighthouse#develop');
    process.exit(1);
  }
}
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/manual-chrome-launcher.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/manual-chrome-launcher.js

Statements: 69.23% (9 / 13)      Branches: 50% (1 / 2)      Functions: 100% (0 / 0)      Lines: 81.82% (9 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                        1   1   1 1   1         1 1         1 1      
//#!/usr/bin/env node
 
'use strict'
/**
 * @fileoverview Script to launch a clean Chrome instance on-demand.
 * Assuming Lighthouse is installed globally or `npm link`ed, use via:
 *     chrome-debug
 * Optionally pass additional flags and/or a URL
 *     chrome-debug http://goat.com
 *     chrome-debug --show-paint-rects
 */
 
require('./compiled-check.js')('chrome-launcher.js');
 
const args = process.argv.slice(2);
 
let additionalFlags;
let startingUrl;
 
Iif (args.length) {
  additionalFlags = args.filter(flag => flag.startsWith('--'));
  startingUrl = args.find(flag => !flag.startsWith('--'));
}
 
const ChromeLauncher = require('./chrome-launcher.js').ChromeLauncher;
const chromeInstance = new ChromeLauncher({
  startingUrl,
  additionalFlags,
});
 
chromeInstance.prepare();
chromeInstance.run();
 
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/printer.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/printer.js

Statements: 33.33% (30 / 90)      Branches: 7.14% (3 / 42)      Functions: 37.5% (3 / 8)      Lines: 32.58% (29 / 89)      Ignored: 6 statements, 1 function, 1 branch     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176                                  1             1 1 1 1 1 1   1   1 1 1 1       1             1 1                                     1                                                                                                       1         1 1   1 1 1             1                             1               1             1 1 2         1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * An enumeration of acceptable output modes:
 *   'pretty': Pretty print the results
 *   'json': JSON formatted results
 *   'html': An HTML report
 */
var OutputMode;
(function (OutputMode) {
    OutputMode[OutputMode["pretty"] = 0] = "pretty";
    OutputMode[OutputMode["json"] = 1] = "json";
    OutputMode[OutputMode["html"] = 2] = "html";
    OutputMode[OutputMode["none"] = 3] = "none";
})(OutputMode || (OutputMode = {}));
exports.OutputMode = OutputMode;
;
const fs = require('fs');
const ReportGenerator = require('../lighthouse-core/report/report-generator');
const Formatter = require('../lighthouse-core/formatters/formatter');
const log = require('../lighthouse-core/lib/log');
/**
 * Verify output path to use, either stdout or a file path.
 */
function checkOutputPath(path) {
    if (!path) {
        log.warn('Printer', 'No output path set; using stdout');
        return 'stdout';
    }
    return path;
}
exports.checkOutputPath = checkOutputPath;
function formatAggregationResultItem(score, suffix = '') {
    if (typeof score === 'boolean') {
        return score ? `${log.greenify(log.tick)}` : `${log.redify(log.cross)}`;
    }
    if (typeof score !== 'number') {
        return `${log.purple}${score}${log.reset}`;
    }
    let colorChoice = log.red;
    if (score > 45) {
        colorChoice = log.yellow;
    }
    if (score > 75) {
        colorChoice = log.green;
    }
    return `${colorChoice}${score}${suffix}${log.reset}`;
}
/**
 * Creates the results output in a format based on the `mode`.
 */
function createOutput(results, outputMode) {
    const reportGenerator = new ReportGenerator();
    // HTML report.
    if (outputMode === OutputMode.html) {
        return reportGenerator.generateHTML(results, 'cli');
    }
    // JSON report.
    if (outputMode === OutputMode.json) {
        return JSON.stringify(results, null, 2);
    }
    // No report (the new default)
    if (outputMode === OutputMode.none)
        return '';
    // Pretty printed CLI report.
    const version = results.lighthouseVersion;
    let output = `\n\n${log.bold}Lighthouse (${version}) results:${log.reset} ${results.url}\n\n`;
    results.aggregations.forEach(aggregation => {
        const total = aggregation.total ? ': ' + formatAggregationResultItem(Math.round(aggregation.total * 100), '%') : '';
        output += `${log.whiteSmallSquare} ${log.bold}${aggregation.name}${log.reset}${total}\n\n`;
        aggregation.score.forEach(item => {
            const score = (item.overall * 100).toFixed(0);
            if (item.name) {
                output += `${log.bold}${item.name}${log.reset}: ${item.scored ? formatAggregationResultItem(score, '%') : ''}\n`;
            }
            item.subItems.forEach(subitem => {
                let auditResult;
                if (typeof subitem === 'string') {
                    auditResult = results.audits[subitem];
                }
                else {
                    auditResult = subitem;
                }
                const formattedScore = auditResult.error ? `${log.redify('‽')}` :
                    `${formatAggregationResultItem(auditResult.score)}`;
                let lineItem = ` ${log.doubleLightHorizontal} ${formattedScore} ${auditResult.description}`;
                if (auditResult.displayValue) {
                    lineItem += ` (${log.bold}${auditResult.displayValue}${log.reset})`;
                }
                output += `${lineItem}\n`;
                if (auditResult.debugString) {
                    output += `    ${auditResult.debugString}\n`;
                }
                if (auditResult.extendedInfo && auditResult.extendedInfo.value) {
                    const formatter = Formatter.getByName(auditResult.extendedInfo.formatter).getFormatter('pretty');
                    output += `${formatter(auditResult.extendedInfo.value)}`;
                }
            });
            output += '\n';
        });
    });
    return output;
}
exports.createOutput = createOutput;
/* istanbul ignore next */
/**
 * Writes the output to stdout.
 */
function writeToStdout(output) {
    return new Promise((resolve, reject) => {
        // small delay to avoid race with debug() logs
        setTimeout(_ => {
            process.stdout.write(`${output}\n`);
            resolve();
        }, 50);
    });
}
/**
 * Writes the output to a file.
 */
function writeFile(filePath, output, outputMode) {
    return new Promise((resolve, reject) => {
        // TODO: make this mkdir to the filePath.
        fs.writeFile(filePath, output, 'utf8', (err) => {
            if (err) {
                return reject(err);
            }
            log.log('Printer', `${OutputMode[outputMode]} output written to ${filePath}`);
            resolve();
        });
    });
}
/**
 * Writes the results.
 */
function write(results, mode, path) {
    return new Promise((resolve, reject) => {
        const outputPath = checkOutputPath(path);
        const output = createOutput(results, OutputMode[mode]);
        // Testing stdout is out of scope, and doesn't really achieve much besides testing Node,
        // so we will skip this chunk of the code.
        /* istanbul ignore if */
        if (outputPath === 'stdout') {
            return writeToStdout(output).then(_ => resolve(results));
        }
        return writeFile(outputPath, output, OutputMode[mode]).then(_ => {
            resolve(results);
        }).catch(err => reject(err));
    });
}
exports.write = write;
function GetValidOutputOptions() {
    return [OutputMode[OutputMode.pretty],
        OutputMode[OutputMode.json],
        OutputMode[OutputMode.html],
        OutputMode[OutputMode.none]];
}
exports.GetValidOutputOptions = GetValidOutputOptions;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHJpbnRlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInByaW50ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7Ozs7Ozs7Ozs7OztHQWVHO0FBRUgsWUFBWSxDQUFDOztBQUViOzs7OztHQUtHO0FBQ0gsSUFBSyxVQUF1QztBQUE1QyxXQUFLLFVBQVU7SUFBRywrQ0FBTSxDQUFBO0lBQUUsMkNBQUksQ0FBQTtJQUFFLDJDQUFJLENBQUE7SUFBRSwyQ0FBSSxDQUFBO0FBQUMsQ0FBQyxFQUF2QyxVQUFVLEtBQVYsVUFBVSxRQUE2QjtBQTRLMUMsZ0NBQVU7QUE1S2dDLENBQUM7QUFLN0MsTUFBTSxFQUFFLEdBQUcsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDO0FBQ3pCLE1BQU0sZUFBZSxHQUFHLE9BQU8sQ0FBQyw0Q0FBNEMsQ0FBQyxDQUFDO0FBQzlFLE1BQU0sU0FBUyxHQUFHLE9BQU8sQ0FBQyx5Q0FBeUMsQ0FBQyxDQUFDO0FBQ3JFLE1BQU0sR0FBRyxHQUFHLE9BQU8sQ0FBQyw0QkFBNEIsQ0FBQyxDQUFDO0FBR2xEOztHQUVHO0FBQ0gseUJBQXlCLElBQVk7SUFDbkMsRUFBRSxDQUFDLENBQUMsQ0FBQyxJQUFJLENBQUMsQ0FBQyxDQUFDO1FBQ1YsR0FBRyxDQUFDLElBQUksQ0FBQyxTQUFTLEVBQUUsa0NBQWtDLENBQUMsQ0FBQztRQUN4RCxNQUFNLENBQUMsUUFBUSxDQUFDO0lBQ2xCLENBQUM7SUFFRCxNQUFNLENBQUMsSUFBSSxDQUFDO0FBQ2QsQ0FBQztBQW9KQywwQ0FBZTtBQWxKakIscUNBQXFDLEtBQWdDLEVBQUUsTUFBTSxHQUFHLEVBQUU7SUFDaEYsRUFBRSxDQUFDLENBQUMsT0FBTyxLQUFLLEtBQUssU0FBUyxDQUFDLENBQUMsQ0FBQztRQUMvQixNQUFNLENBQUMsS0FBSyxHQUFHLEdBQUcsR0FBRyxDQUFDLFFBQVEsQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDLEVBQUUsR0FBRyxHQUFHLEdBQUcsQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxFQUFFLENBQUM7SUFDMUUsQ0FBQztJQUNELEVBQUUsQ0FBQyxDQUFDLE9BQU8sS0FBSyxLQUFLLFFBQVEsQ0FBQyxDQUFDLENBQUM7UUFDOUIsTUFBTSxDQUFDLEdBQUcsR0FBRyxDQUFDLE1BQU0sR0FBRyxLQUFLLEdBQUcsR0FBRyxDQUFDLEtBQUssRUFBRSxDQUFDO0lBQzdDLENBQUM7SUFFRCxJQUFJLFdBQVcsR0FBRyxHQUFHLENBQUMsR0FBRyxDQUFDO0lBQzFCLEVBQUUsQ0FBQyxDQUFDLEtBQUssR0FBRyxFQUFFLENBQUMsQ0FBQyxDQUFDO1FBQ2YsV0FBVyxHQUFHLEdBQUcsQ0FBQyxNQUFNLENBQUM7SUFDM0IsQ0FBQztJQUNELEVBQUUsQ0FBQyxDQUFDLEtBQUssR0FBRyxFQUFFLENBQUMsQ0FBQyxDQUFDO1FBQ2YsV0FBVyxHQUFHLEdBQUcsQ0FBQyxLQUFLLENBQUM7SUFDMUIsQ0FBQztJQUNELE1BQU0sQ0FBQyxHQUFHLFdBQVcsR0FBRyxLQUFLLEdBQUcsTUFBTSxHQUFHLEdBQUcsQ0FBQyxLQUFLLEVBQUUsQ0FBQztBQUN2RCxDQUFDO0FBRUQ7O0dBRUc7QUFDSCxzQkFBc0IsT0FBZ0IsRUFBRSxVQUFzQjtJQUM1RCxNQUFNLGVBQWUsR0FBRyxJQUFJLGVBQWUsRUFBRSxDQUFDO0lBRTlDLGVBQWU7SUFDZixFQUFFLENBQUMsQ0FBQyxVQUFVLEtBQUssVUFBVSxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUM7UUFDbkMsTUFBTSxDQUFDLGVBQWUsQ0FBQyxZQUFZLENBQUMsT0FBTyxFQUFFLEtBQUssQ0FBQyxDQUFDO0lBQ3RELENBQUM7SUFFRCxlQUFlO0lBQ2YsRUFBRSxDQUFDLENBQUMsVUFBVSxLQUFLLFVBQVUsQ0FBQyxJQUFJLENBQUMsQ0FBQyxDQUFDO1FBQ25DLE1BQU0sQ0FBQyxJQUFJLENBQUMsU0FBUyxDQUFDLE9BQU8sRUFBRSxJQUFJLEVBQUUsQ0FBQyxDQUFDLENBQUM7SUFDMUMsQ0FBQztJQUVELDhCQUE4QjtJQUM5QixFQUFFLENBQUMsQ0FBQyxVQUFVLEtBQUssVUFBVSxDQUFDLElBQUksQ0FBQztRQUFDLE1BQU0sQ0FBQyxFQUFFLENBQUM7SUFFOUMsNkJBQTZCO0lBQzdCLE1BQU0sT0FBTyxHQUFHLE9BQU8sQ0FBQyxpQkFBaUIsQ0FBQztJQUMxQyxJQUFJLE1BQU0sR0FBRyxPQUFPLEdBQUcsQ0FBQyxJQUFJLGVBQWUsT0FBTyxhQUFhLEdBQUcsQ0FBQyxLQUFLLElBQUksT0FBTyxDQUFDLEdBQUcsTUFBTSxDQUFDO0lBRTlGLE9BQU8sQ0FBQyxZQUFZLENBQUMsT0FBTyxDQUFDLFdBQVc7UUFDdEMsTUFBTSxLQUFLLEdBQUcsV0FBVyxDQUFDLEtBQUssR0FBRyxJQUFJLEdBQUcsMkJBQTJCLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxXQUFXLENBQUMsS0FBSyxHQUFHLEdBQUcsQ0FBQyxFQUFFLEdBQUcsQ0FBQyxHQUFHLEVBQUUsQ0FBQztRQUNwSCxNQUFNLElBQUksR0FBRyxHQUFHLENBQUMsZ0JBQWdCLElBQUksR0FBRyxDQUFDLElBQUksR0FBRyxXQUFXLENBQUMsSUFBSSxHQUFHLEdBQUcsQ0FBQyxLQUFLLEdBQUcsS0FBSyxNQUFNLENBQUM7UUFFM0YsV0FBVyxDQUFDLEtBQUssQ0FBQyxPQUFPLENBQUMsSUFBSTtZQUM1QixNQUFNLEtBQUssR0FBRyxDQUFDLElBQUksQ0FBQyxPQUFPLEdBQUcsR0FBRyxDQUFDLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDO1lBRTlDLEVBQUUsQ0FBQyxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQyxDQUFDO2dCQUNkLE1BQU0sSUFBSSxHQUFHLEdBQUcsQ0FBQyxJQUFJLEdBQUcsSUFBSSxDQUFDLElBQUksR0FBRyxHQUFHLENBQUMsS0FBSyxLQUFLLElBQUksQ0FBQyxNQUFNLEdBQUcsMkJBQTJCLENBQUMsS0FBSyxFQUFFLEdBQUcsQ0FBQyxHQUFHLEVBQUUsSUFBSSxDQUFDO1lBQ25ILENBQUM7WUFFRCxJQUFJLENBQUMsUUFBUSxDQUFDLE9BQU8sQ0FBQyxPQUFPO2dCQUMzQixJQUFJLFdBQXdCLENBQUM7Z0JBRTdCLEVBQUUsQ0FBQyxDQUFDLE9BQU8sT0FBTyxLQUFLLFFBQVEsQ0FBQyxDQUFDLENBQUM7b0JBQ2hDLFdBQVcsR0FBUyxPQUFRLENBQUMsTUFBTSxDQUFDLE9BQU8sQ0FBQyxDQUFDO2dCQUMvQyxDQUFDO2dCQUFDLElBQUksQ0FBQyxDQUFDO29CQUNOLFdBQVcsR0FBRyxPQUFzQixDQUFDO2dCQUN2QyxDQUFDO2dCQUVELE1BQU0sY0FBYyxHQUFHLFdBQVcsQ0FBQyxLQUFLLEdBQUcsR0FBRyxHQUFHLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxFQUFFO29CQUMzRCxHQUFHLDJCQUEyQixDQUFDLFdBQVcsQ0FBQyxLQUFLLENBQUMsRUFBRSxDQUFDO2dCQUN4RCxJQUFJLFFBQVEsR0FBRyxJQUFJLEdBQUcsQ0FBQyxxQkFBcUIsSUFBSSxjQUFjLElBQUksV0FBVyxDQUFDLFdBQVcsRUFBRSxDQUFDO2dCQUM1RixFQUFFLENBQUMsQ0FBQyxXQUFXLENBQUMsWUFBWSxDQUFDLENBQUMsQ0FBQztvQkFDN0IsUUFBUSxJQUFJLEtBQUssR0FBRyxDQUFDLElBQUksR0FBRyxXQUFXLENBQUMsWUFBWSxHQUFHLEdBQUcsQ0FBQyxLQUFLLEdBQUcsQ0FBQztnQkFDdEUsQ0FBQztnQkFDRCxNQUFNLElBQUksR0FBRyxRQUFRLElBQUksQ0FBQztnQkFDMUIsRUFBRSxDQUFDLENBQUMsV0FBVyxDQUFDLFdBQVcsQ0FBQyxDQUFDLENBQUM7b0JBQzVCLE1BQU0sSUFBSSxPQUFPLFdBQVcsQ0FBQyxXQUFXLElBQUksQ0FBQztnQkFDL0MsQ0FBQztnQkFFRCxFQUFFLENBQUMsQ0FBQyxXQUFXLENBQUMsWUFBWSxJQUFJLFdBQVcsQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQztvQkFDL0QsTUFBTSxTQUFTLEdBQ1gsU0FBUyxDQUFDLFNBQVMsQ0FBQyxXQUFXLENBQUMsWUFBWSxDQUFDLFNBQVMsQ0FBQyxDQUFDLFlBQVksQ0FBQyxRQUFRLENBQUMsQ0FBQztvQkFDbkYsTUFBTSxJQUFJLEdBQUcsU0FBUyxDQUFDLFdBQVcsQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLEVBQUUsQ0FBQztnQkFDM0QsQ0FBQztZQUNILENBQUMsQ0FBQyxDQUFDO1lBRUgsTUFBTSxJQUFJLElBQUksQ0FBQztRQUNqQixDQUFDLENBQUMsQ0FBQztJQUNMLENBQUMsQ0FBQyxDQUFDO0lBRUgsTUFBTSxDQUFDLE1BQU0sQ0FBQztBQUNoQixDQUFDO0FBK0RDLG9DQUFZO0FBN0RkLDBCQUEwQjtBQUMxQjs7R0FFRztBQUNILHVCQUF1QixNQUFjO0lBQ25DLE1BQU0sQ0FBQyxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxNQUFNO1FBQ2pDLDhDQUE4QztRQUM5QyxVQUFVLENBQUMsQ0FBQztZQUNWLE9BQU8sQ0FBQyxNQUFNLENBQUMsS0FBSyxDQUFDLEdBQUcsTUFBTSxJQUFJLENBQUMsQ0FBQztZQUNwQyxPQUFPLEVBQUUsQ0FBQztRQUNaLENBQUMsRUFBRSxFQUFFLENBQUMsQ0FBQztJQUNULENBQUMsQ0FBQyxDQUFDO0FBQ0wsQ0FBQztBQUVEOztHQUVHO0FBQ0gsbUJBQW1CLFFBQWdCLEVBQUUsTUFBYyxFQUFFLFVBQXNCO0lBQ3pFLE1BQU0sQ0FBQyxJQUFJLE9BQU8sQ0FBQyxDQUFDLE9BQU8sRUFBRSxNQUFNO1FBQ2pDLHlDQUF5QztRQUN6QyxFQUFFLENBQUMsU0FBUyxDQUFDLFFBQVEsRUFBRSxNQUFNLEVBQUUsTUFBTSxFQUFFLENBQUMsR0FBVTtZQUNoRCxFQUFFLENBQUMsQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDO2dCQUNSLE1BQU0sQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLENBQUM7WUFDckIsQ0FBQztZQUNELEdBQUcsQ0FBQyxHQUFHLENBQUMsU0FBUyxFQUFFLEdBQUcsVUFBVSxDQUFDLFVBQVUsQ0FBQyxzQkFBc0IsUUFBUSxFQUFFLENBQUMsQ0FBQztZQUM5RSxPQUFPLEVBQUUsQ0FBQztRQUNaLENBQUMsQ0FBQyxDQUFDO0lBQ0wsQ0FBQyxDQUFDLENBQUM7QUFDTCxDQUFDO0FBRUQ7O0dBRUc7QUFDSCxlQUFlLE9BQWdCLEVBQUUsSUFBVSxFQUFFLElBQVk7SUFDdkQsTUFBTSxDQUFDLElBQUksT0FBTyxDQUFDLENBQUMsT0FBTyxFQUFFLE1BQU07UUFDakMsTUFBTSxVQUFVLEdBQUcsZUFBZSxDQUFDLElBQUksQ0FBQyxDQUFDO1FBRXpDLE1BQU0sTUFBTSxHQUFHLFlBQVksQ0FBQyxPQUFPLEVBQVEsVUFBVyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUM7UUFFOUQsd0ZBQXdGO1FBQ3hGLDBDQUEwQztRQUMxQyx3QkFBd0I7UUFDeEIsRUFBRSxDQUFDLENBQUMsVUFBVSxLQUFLLFFBQVEsQ0FBQyxDQUFDLENBQUM7WUFDNUIsTUFBTSxDQUFDLGFBQWEsQ0FBQyxNQUFNLENBQUMsQ0FBQyxJQUFJLENBQUMsQ0FBQyxJQUFJLE9BQU8sQ0FBQyxPQUFPLENBQUMsQ0FBQyxDQUFDO1FBQzNELENBQUM7UUFFRCxNQUFNLENBQUMsU0FBUyxDQUFDLFVBQVUsRUFBRSxNQUFNLEVBQVEsVUFBVyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsSUFBSSxDQUFDLENBQUM7WUFDbEUsT0FBTyxDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQ25CLENBQUMsQ0FBQyxDQUFDLEtBQUssQ0FBQyxHQUFHLElBQUksTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUM7SUFDL0IsQ0FBQyxDQUFDLENBQUM7QUFDTCxDQUFDO0FBWUMsc0JBQUs7QUFWUDtJQUNFLE1BQU0sQ0FBQyxDQUFDLFVBQVUsQ0FBQyxVQUFVLENBQUMsTUFBTSxDQUFTO1FBQ3JDLFVBQVUsQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFTO1FBQ25DLFVBQVUsQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFTO1FBQ25DLFVBQVUsQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFTLENBQUMsQ0FBQztBQUMvQyxDQUFDO0FBT0Msc0RBQXFCIn0=
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/random-port.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/random-port.js

Statements: 33.33% (4 / 12)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 36.36% (4 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36                                  1 1       1                     1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
const http_1 = require("http");
/**
 * Return a random, unused port.
 */
function getRandomPort() {
    return new Promise((resolve, reject) => {
        const server = http_1.createServer();
        server.listen(0);
        server.once('listening', () => {
            const port = server.address().port;
            server.close(() => resolve(port));
        });
        server.once('error', reject);
    });
}
exports.getRandomPort = getRandomPort;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmFuZG9tLXBvcnQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJyYW5kb20tcG9ydC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7Ozs7Ozs7Ozs7O0dBZUc7QUFDSCxZQUFZLENBQUM7O0FBRWIsK0JBQWtDO0FBRWxDOztHQUVHO0FBQ0g7SUFDRSxNQUFNLENBQUMsSUFBSSxPQUFPLENBQUMsQ0FBQyxPQUFPLEVBQUUsTUFBTTtRQUNqQyxNQUFNLE1BQU0sR0FBRyxtQkFBWSxFQUFFLENBQUM7UUFDOUIsTUFBTSxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUNqQixNQUFNLENBQUMsSUFBSSxDQUFDLFdBQVcsRUFBRTtZQUN2QixNQUFNLElBQUksR0FBRyxNQUFNLENBQUMsT0FBTyxFQUFFLENBQUMsSUFBSSxDQUFDO1lBQ25DLE1BQU0sQ0FBQyxLQUFLLENBQUMsTUFBTSxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQztRQUNwQyxDQUFDLENBQUMsQ0FBQztRQUNILE1BQU0sQ0FBQyxJQUFJLENBQUMsT0FBTyxFQUFFLE1BQU0sQ0FBQyxDQUFDO0lBQy9CLENBQUMsQ0FBQyxDQUFDO0FBQ0wsQ0FBQztBQUdDLHNDQUFhIn0=
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/commands/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/commands/

Statements: 65% (13 / 20)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 68.42% (13 / 19)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/commands/
File Statements Branches Functions Lines
commands.js 100% (5 / 5) 100% (0 / 0) 100% (0 / 0) 100% (5 / 5)
list-audits.js 50% (4 / 8) 100% (0 / 0) 0% (0 / 1) 57.14% (4 / 7)
list-trace-categories.js 57.14% (4 / 7) 100% (0 / 0) 0% (0 / 1) 57.14% (4 / 7)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/commands/commands.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/commands/commands.js

Statements: 100% (5 / 5)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (5 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24                                  1 1 1 1 1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const list_audits_1 = require("./list-audits");
exports.ListAudits = list_audits_1.default;
const list_trace_categories_1 = require("./list-trace-categories");
exports.ListTraceCategories = list_trace_categories_1.default;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29tbWFuZHMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJjb21tYW5kcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7Ozs7Ozs7Ozs7O0dBZUc7OztBQUVILCtDQUF1QztBQUlyQywyQ0FBVTtBQUhaLG1FQUEwRDtBQUl4RCw4REFBbUIifQ==
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/commands/list-audits.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/commands/list-audits.js

Statements: 50% (4 / 8)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 57.14% (4 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27                                  1 1 1         1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const lighthouse = require('../../lighthouse-core');
function ListAudits() {
    const audits = lighthouse.getAuditList().map((i) => i.replace(/\.js$/, ''));
    process.stdout.write(JSON.stringify({ audits }, null, 2));
    process.exit(0);
}
exports.default = ListAudits;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibGlzdC1hdWRpdHMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJsaXN0LWF1ZGl0cy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7Ozs7Ozs7Ozs7O0dBZUc7OztBQUVILE1BQU0sVUFBVSxHQUFHLE9BQU8sQ0FBQyx1QkFBdUIsQ0FBQyxDQUFDO0FBRXBEO0lBQ0UsTUFBTSxNQUFNLEdBQUcsVUFBVSxDQUFDLFlBQVksRUFBRSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQVMsS0FBSyxDQUFDLENBQUMsT0FBTyxDQUFDLE9BQU8sRUFBRSxFQUFFLENBQUMsQ0FBQyxDQUFDO0lBRXBGLE9BQU8sQ0FBQyxNQUFNLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxTQUFTLENBQUMsRUFBQyxNQUFNLEVBQUMsRUFBRSxJQUFJLEVBQUUsQ0FBQyxDQUFDLENBQUMsQ0FBQztJQUN4RCxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDO0FBQ2xCLENBQUM7QUFMRCw2QkFLQyJ9
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/commands/list-trace-categories.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/commands/list-trace-categories.js

Statements: 57.14% (4 / 7)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 57.14% (4 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27                                  1 1 1         1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const lighthouse = require('../../lighthouse-core');
function listTraceCategories() {
    const traceCategories = lighthouse.traceCategories;
    process.stdout.write(JSON.stringify({ traceCategories }));
    process.exit(0);
}
exports.default = listTraceCategories;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibGlzdC10cmFjZS1jYXRlZ29yaWVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsibGlzdC10cmFjZS1jYXRlZ29yaWVzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7Ozs7Ozs7Ozs7R0FlRzs7O0FBRUgsTUFBTSxVQUFVLEdBQUcsT0FBTyxDQUFDLHVCQUF1QixDQUFDLENBQUM7QUFFcEQ7SUFDRSxNQUFNLGVBQWUsR0FBRyxVQUFVLENBQUMsZUFBZSxDQUFDO0lBRW5ELE9BQU8sQ0FBQyxNQUFNLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxTQUFTLENBQUMsRUFBQyxlQUFlLEVBQUMsQ0FBQyxDQUFDLENBQUM7SUFDeEQsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQztBQUNsQixDQUFDO0FBTEQsc0NBS0MifQ==
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/

Statements: 19.51% (16 / 82)      Branches: 0% (0 / 16)      Functions: 0% (0 / 5)      Lines: 20.25% (16 / 79)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/
File Statements Branches Functions Lines
server.js 19.51% (16 / 82) 0% (0 / 16) 0% (0 / 5) 20.25% (16 / 79)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/server.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/server.js

Statements: 19.51% (16 / 82)      Branches: 0% (0 / 16)      Functions: 0% (0 / 5)      Lines: 20.25% (16 / 79)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160                                                          1 1 1 1 1 1 1   1 1 1 1             1                                         1                                                             1                                             1                                                                 1        
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
/**
 * @fileoverview Server script for Project Performance Experiment.
 *
 * Functionality:
 *    Host experiment.
 *    Report can be access via URL: /?id=[REPORT_ID]
 *    Browser can request lighthousr rerun by sending POST request to URL: /rerun?id=[REPORT_ID]
 *      This will rerun lighthouse with additional cli-flags received from POST request data and
 *      return the new report id
 */
 
const http = require('http');
const parse = require('url').parse;
const opn = require('opn');
const log = require('../../lighthouse-core/lib/log');
const lighthouse = require('../../lighthouse-core');
const ExperimentDatabase = require('./experiment-database/database');
const PerfXReportGenerator = require('./report/perf-x-report-generator');
 
let database;
let fallbackReportId;
let url;
let config;
/**
 * Start the server with an arbitrary port and open report page in the default browser.
 * @param {!Object} params A JSON contains lighthouse parameters
 * @param {!Object} results
 * @return {!Promise<string>} Promise that resolves when server is closed
 */
function hostExperiment(params, results) {
  return new Promise(resolve => {
    url = params.url;
    config = params.config;
 
    database = new ExperimentDatabase();
    const id = database.saveData(params.flags, results);
    fallbackReportId = id;
 
    const server = http.createServer(requestHandler);
    server.listen(0);
    server.on('listening', () => opn(`http://localhost:${server.address().port}/?id=${id}`));
    server.on('error', err => log.error('PerformanceXServer', err.code, err));
    server.on('close', resolve);
    process.on('SIGINT', () => {
      database.clear();
      server.close();
    });
  });
}
 
function requestHandler(request, response) {
  request.parsedUrl = parse(request.url, true);
  const pathname = request.parsedUrl.pathname;
  try {
    if (request.method === 'GET') {
      if (pathname === '/') {
        reportRequestHandler(request, response);
      } else {
        throw new HTTPError(404);
      }
    } else if (request.method === 'POST') {
      if (pathname === '/rerun') {
        rerunRequestHandler(request, response);
      } else {
        throw new HTTPError(404);
      }
    } else {
      throw new HTTPError(405);
    }
  } catch (err) {
    if (err instanceof HTTPError) {
      response.writeHead(err.statusCode);
      response.end(err.message || http.STATUS_CODES[err.statusCode]);
    } else {
      response.writeHead(500);
      response.end(http.STATUS_CODES[500]);
      log.err('PerformanceXServer', err.code, err);
    }
  }
}
 
function reportRequestHandler(request, response) {
  try {
    const id = request.parsedUrl.query.id || fallbackReportId;
 
    const reportsMetadata = Object.keys(database.timeStamps).map(key => {
      const generatedTime = database.timeStamps[key];
      return {url, reportHref: `/?id=${key}`, generatedTime};
    });
    reportsMetadata.sort((metadata1, metadata2) => {
      return new Date(metadata1.generatedTime) - new Date(metadata2.generatedTime);
    });
    const reportsCatalog = {reportsMetadata, selectedReportHref: `/?id=${id}`};
 
    const results = database.getResults(id);
    const perfXReportGenerator = new PerfXReportGenerator();
 
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.end(perfXReportGenerator.generateHTML(results, 'perf-x', reportsCatalog));
  } catch (err) {
    throw new HTTPError(404);
  }
}
 
function rerunRequestHandler(request, response) {
  try {
    const flags = database.getFlags(request.parsedUrl.query.id || fallbackReportId);
    let message = '';
    request.on('data', data => message += data);
 
    request.on('end', () => {
      const additionalFlags = JSON.parse(message);
      Object.assign(flags, additionalFlags);
 
      lighthouse(url, flags, config).then(results => {
        results.artifacts = undefined;
        const id = database.saveData(flags, results);
        response.writeHead(200);
        response.end(id);
      }).catch(err => {
        log.error('PerformanceXServer', err.code, err);
        response.writeHead(500);
        response.end(http.STATUS_CODES[500]);
      });
    });
  } catch (err) {
    throw new HTTPError(404);
  }
}
 
class HTTPError extends Error {
  constructor(statusCode, message) {
    super(message);
    this.statusCode = statusCode;
  }
}
 
module.exports = {
  hostExperiment
};
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/experiment-database/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/experiment-database/

Statements: 26.32% (5 / 19)      Branches: 100% (0 / 0)      Functions: 0% (0 / 7)      Lines: 26.32% (5 / 19)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/experiment-database/
File Statements Branches Functions Lines
database.js 26.32% (5 / 19) 100% (0 / 0) 0% (0 / 7) 26.32% (5 / 19)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/experiment-database/database.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/experiment-database/database.js

Statements: 26.32% (5 / 19)      Branches: 100% (0 / 0)      Functions: 0% (0 / 7)      Lines: 26.32% (5 / 19)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81                                      1 1 1 1                                                                                                               1    
/**
 * @license
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const fs = require('fs');
const path = require('path');
const rimraf = require('rimraf');
const getFilenamePrefix = require('../../../lighthouse-core/lib/file-namer').getFilenamePrefix;
 
class ExperimentDatabase {
  constructor() {
    this._fsRoot = fs.mkdtempSync(`${__dirname}/experiment-data-`);
    this._timeStamps = {};
  }
 
  get timeStamps() {
    return this._timeStamps;
  }
 
  get fsRoot() {
    return this._fsRoot;
  }
 
  /*
   * Save experiment data
   * @param {!Object} lhFlags
   * @param {!Object} lhResults
   */
  saveData(lhFlags, lhResults) {
    const id = getFilenamePrefix(lhResults);
    this._timeStamps[id] = lhResults.generatedTime;
 
    const dirPath = path.join(this._fsRoot, id);
    fs.mkdirSync(dirPath);
    fs.writeFileSync(path.join(dirPath, 'flags.json'), JSON.stringify(lhFlags));
    fs.writeFileSync(path.join(dirPath, 'results.json'), JSON.stringify(lhResults));
    return id;
  }
 
  /*
   * Get report.html
   * @param {string} id
   */
  getResults(id) {
    return JSON.parse(fs.readFileSync(path.join(this._fsRoot, id, 'results.json'), 'utf8'));
  }
 
  /*
   * Get flags.json
   * @param {string} id
   */
  getFlags(id) {
    return JSON.parse(fs.readFileSync(path.join(this._fsRoot, id, 'flags.json'), 'utf8'));
  }
 
  /*
   * Delete all the files created by this object
   */
  clear() {
    rimraf.sync(this._fsRoot);
  }
}
 
module.exports = ExperimentDatabase;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/report/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/report/

Statements: 46.15% (6 / 13)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 46.15% (6 / 13)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/report/
File Statements Branches Functions Lines
perf-x-report-generator.js 46.15% (6 / 13) 100% (0 / 0) 0% (0 / 2) 46.15% (6 / 13)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/report/perf-x-report-generator.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-cli/performance-experiment/report/perf-x-report-generator.js

Statements: 46.15% (6 / 13)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 46.15% (6 / 13)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45                                        1 1 1 1 1                                   1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
 
'use strict';
 
const fs = require('fs');
const path = require('path');
const Handlebars = require('handlebars');
const ReportGenerator = require('../../../lighthouse-core/report/report-generator');
const configPanelPartial = fs.readFileSync(path.join(__dirname, 'partials/config-panel.html'),
    'utf8');
 
class PerfXReportGenerator extends ReportGenerator {
  getReportJS(reportContext) {
    const scriptArr = super.getReportJS(reportContext);
    scriptArr.push(fs.readFileSync(path.join(__dirname, 'scripts/perf-x.js'), 'utf8'));
    return scriptArr;
  }
 
  _registerFormatters(audits) {
    super._registerFormatters(audits);
    const configPanelTemplate = Handlebars.compile(configPanelPartial);
    const criticalRequestChains = audits['critical-request-chains'].extendedInfo.value;
    Handlebars.registerPartial('config-panel', configPanelTemplate(criticalRequestChains));
  }
}
 
module.exports = PerfXReportGenerator;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/

Statements: 14.96% (19 / 127)      Branches: 0% (0 / 58)      Functions: 0% (0 / 7)      Lines: 15.2% (19 / 125)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/
File Statements Branches Functions Lines
index.js 52.94% (9 / 17) 0% (0 / 4) 0% (0 / 1) 52.94% (9 / 17)
runner.js 9.09% (10 / 110) 0% (0 / 54) 0% (0 / 6) 9.26% (10 / 108)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/index.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/index.js

Statements: 52.94% (9 / 17)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 52.94% (9 / 17)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                                      1 1 1 1                                 1                                       1 1 1 1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Runner = require('./runner');
const log = require('./lib/log.js');
const ChromeProtocol = require('./gather/connections/cri.js');
const Config = require('./config/config');
 
/**
 * The relationship between these root modules:
 *
 *   index.js  - the require('lighthouse') hook for Node modules (including the CLI)
 *
 *   runner.js - marshalls the actions that must be taken (Gather / Audit / Aggregate)
 *               config file is used to determine which of these actions are needed
 *
 *   lighthouse-cli \
 *                   -- index.js  \
 *                                 ----- runner.js ----> [Gather / Audit / Aggregate]
 *           lighthouse-extension /
 *
 */
 
module.exports = function(url, flags = {}, configJSON) {
  return new Promise((resolve, reject) => {
    if (!url) {
      return reject(new Error('Lighthouse requires a URL'));
    }
 
    // set logging preferences, assume quiet
    flags.logLevel = flags.logLevel || 'error';
    log.setLevel(flags.logLevel);
 
    // Use ConfigParser to generate a valid config file
    const config = new Config(configJSON, flags.configPath);
 
    const connection = new ChromeProtocol(flags.port);
 
    // kick off a lighthouse run
    resolve(Runner.run(connection, {url, flags, config}));
  });
};
 
module.exports.getAuditList = Runner.getAuditList;
module.exports.traceCategories = require('./gather/driver').traceCategories;
module.exports.Audit = require('./audits/audit');
module.exports.Gatherer = require('./gather/gatherers/gatherer');
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/runner.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/runner.js

Statements: 9.09% (10 / 110)      Branches: 0% (0 / 54)      Functions: 0% (0 / 6)      Lines: 9.26% (10 / 108)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319                                    1 1 1 1 1 1 1 1 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const Driver = require('./gather/driver.js');
const GatherRunner = require('./gather/gather-runner');
const Aggregate = require('./aggregator/aggregate');
const Audit = require('./audits/audit');
const emulation = require('./lib/emulation');
const log = require('./lib/log');
const fs = require('fs');
const path = require('path');
const URL = require('./lib/url-shim');
 
class Runner {
  static run(connection, opts) {
    // Clean opts input.
    opts.flags = opts.flags || {};
 
    const config = opts.config;
 
    // save the initialUrl provided by the user
    opts.initialUrl = opts.url;
    if (typeof opts.initialUrl !== 'string' || opts.initialUrl.length === 0) {
      return Promise.reject(new Error('You must provide a url to the runner'));
    }
 
    let parsedURL;
    try {
      parsedURL = new URL(opts.url);
    } catch (e) {
      const err = new Error('The url provided should have a proper protocol and hostname.');
      return Promise.reject(err);
    }
 
    // If the URL isn't https and is also not localhost complain to the user.
    if (parsedURL.protocol !== 'https:' && parsedURL.hostname !== 'localhost') {
      log.warn('Lighthouse', 'The URL provided should be on HTTPS');
      log.warn('Lighthouse', 'Performance stats will be skewed redirecting from HTTP to HTTPS.');
    }
 
    // canonicalize URL with any trailing slashes neccessary
    opts.url = parsedURL.href;
 
    // Check that there are passes & audits...
    const validPassesAndAudits = config.passes && config.audits;
 
    // ... or that there are artifacts & audits.
    const validArtifactsAndAudits = config.artifacts && config.audits;
 
    // Make a run, which can be .then()'d with whatever needs to run (based on the config).
    let run = Promise.resolve();
 
    // If there are passes run the GatherRunner and gather the artifacts. If not, we will need
    // to check that there are artifacts specified in the config, and throw if not.
    if (validPassesAndAudits || validArtifactsAndAudits) {
      if (validPassesAndAudits) {
        opts.driver = opts.driverMock || new Driver(connection);
        // Finally set up the driver to gather.
        run = run.then(_ => GatherRunner.run(config.passes, opts));
      } else if (validArtifactsAndAudits) {
        run = run.then(_ => {
          return Object.assign(GatherRunner.instantiateComputedArtifacts(), config.artifacts);
        });
      }
 
      // Basic check that the traces (gathered or loaded) are valid.
      run = run.then(artifacts => {
        for (const passName of Object.keys(artifacts.traces || {})) {
          const trace = artifacts.traces[passName];
          if (!Array.isArray(trace.traceEvents)) {
            throw new Error(passName + ' trace was invalid. `traceEvents` was not an array.');
          }
        }
 
        return artifacts;
      });
 
      // Run each audit sequentially, the auditResults array has all our fine work
      const auditResults = [];
      for (const audit of config.audits) {
        run = run.then(artifacts => {
          return Runner._runAudit(audit, artifacts)
            .then(ret => auditResults.push(ret))
            .then(_ => artifacts);
        });
      }
      run = run.then(artifacts => {
        return {artifacts, auditResults};
      });
    } else if (config.auditResults) {
      // If there are existing audit results, surface those here.
      // Instantiate and return artifacts for consistency.
      const artifacts = Object.assign(GatherRunner.instantiateComputedArtifacts(),
                                      config.artifacts || {});
      run = run.then(_ => {
        return {
          artifacts,
          auditResults: config.auditResults
        };
      });
    } else {
      const err = Error(
          'The config must provide passes and audits, artifacts and audits, or auditResults');
      return Promise.reject(err);
    }
 
    // Format and aggregate results before returning.
    run = run
      .then(runResults => {
        const formattedAudits = runResults.auditResults.reduce((formatted, audit) => {
          formatted[audit.name] = audit;
          return formatted;
        }, {});
 
        // Only run aggregations if needed.
        let aggregations = [];
        if (config.aggregations) {
          aggregations = config.aggregations.map(
            a => Aggregate.aggregate(a, runResults.auditResults));
        }
 
        return {
          lighthouseVersion: require('../package').version,
          generatedTime: (new Date()).toJSON(),
          initialUrl: opts.initialUrl,
          url: opts.url,
          audits: formattedAudits,
          artifacts: runResults.artifacts,
          runtimeConfig: Runner.getRuntimeConfig(opts.flags),
          aggregations
        };
      });
 
    return run;
  }
 
  /**
   * Checks that the audit's required artifacts exist and runs the audit if so.
   * Otherwise returns error audit result.
   * @param {!Audit} audit
   * @param {!Artifacts} artifacts
   * @return {!Promise<!AuditResult>}
   * @private
   */
  static _runAudit(audit, artifacts) {
    const status = `Evaluating: ${audit.meta.description}`;
 
    return Promise.resolve().then(_ => {
      log.log('status', status);
 
      // Return an early error if an artifact required for the audit is missing or an error.
      for (const artifactName of audit.meta.requiredArtifacts) {
        const noArtifact = typeof artifacts[artifactName] === 'undefined';
 
        // If trace required, check that DEFAULT_PASS trace exists.
        // TODO: need pass-specific check of networkRecords and traces.
        const noTrace = artifactName === 'traces' && !artifacts.traces[Audit.DEFAULT_PASS];
 
        if (noArtifact || noTrace) {
          log.warn('Runner',
              `${artifactName} gatherer, required by audit ${audit.meta.name}, did not run.`);
          throw new Error(`Required ${artifactName} gatherer did not run.`);
        }
 
        // If artifact was an error, it must be non-fatal (or gatherRunner would
        // have thrown). Output error result on behalf of audit.
        if (artifacts[artifactName] instanceof Error) {
          const artifactError = artifacts[artifactName];
          log.warn('Runner', `${artifactName} gatherer, required by audit ${audit.meta.name},` +
            ` encountered an error: ${artifactError.message}`);
          throw new Error(
              `Required ${artifactName} gatherer encountered an error: ${artifactError.message}`);
        }
      }
      // all required artifacts are in good shape, so we proceed
      return audit.audit(artifacts);
    }).catch(err => {
      if (err.fatal) {
        throw err;
      }
 
      // Non-fatal error become error audit result.
      return audit.generateErrorAuditResult('Audit error: ' + err.message);
    }).then(result => {
      log.verbose('statusEnd', status);
      return result;
    });
  }
 
  /**
   * Returns list of audit names for external querying.
   * @return {!Array<string>}
   */
  static getAuditList() {
    const ignoredFiles = [
      'audit.js',
      'accessibility/axe-audit.js',
      'byte-efficiency/byte-efficiency-audit.js'
    ];
 
    const fileList = [
      ...fs.readdirSync(path.join(__dirname, './audits')),
      ...fs.readdirSync(path.join(__dirname, './audits/dobetterweb')).map(f => `dobetterweb/${f}`),
      ...fs.readdirSync(path.join(__dirname, './audits/accessibility'))
          .map(f => `accessibility/${f}`),
      ...fs.readdirSync(path.join(__dirname, './audits/byte-efficiency'))
          .map(f => `byte-efficiency/${f}`)
    ];
    return fileList.filter(f => {
      return /\.js$/.test(f) && !ignoredFiles.includes(f);
    }).sort();
  }
 
  /**
   * Returns list of gatherer names for external querying.
   * @return {!Array<string>}
   */
  static getGathererList() {
    const fileList = [
      ...fs.readdirSync(path.join(__dirname, './gather/gatherers')),
      ...fs.readdirSync(path.join(__dirname, './gather/gatherers/dobetterweb'))
          .map(f => `dobetterweb/${f}`)
    ];
    return fileList.filter(f => /\.js$/.test(f) && f !== 'gatherer.js').sort();
  }
 
  /**
   * Resolves the location of the specified plugin and returns an absolute
   * string path to the file. Used for loading custom audits and gatherers.
   * Throws an error if no plugin is found.
   * @param {string} plugin
   * @param {string=} configDir The absolute path to the directory of the config file, if there is one.
   * @param {string=} category Optional plugin category (e.g. 'audit') for better error messages.
   * @return {string}
   * @throws {Error}
   */
  static resolvePlugin(plugin, configDir, category) {
    // First try straight `require()`. Unlikely to be specified relative to this
    // file, but adds support for Lighthouse plugins in npm modules as
    // `require()` walks up parent directories looking inside any node_modules/
    // present. Also handles absolute paths.
    try {
      return require.resolve(plugin);
    } catch (e) {}
 
    // See if the plugin resolves relative to the current working directory.
    // Most useful to handle the case of invoking Lighthouse as a module, since
    // then the config is an object and so has no path.
    const cwdPath = path.resolve(process.cwd(), plugin);
    try {
      return require.resolve(cwdPath);
    } catch (e) {}
 
    const errorString = 'Unable to locate ' +
        (category ? `${category}: ` : '') +
        `${plugin} (tried to require() from '${__dirname}' and load from '${cwdPath}'`;
 
    if (!configDir) {
      throw new Error(errorString + ')');
    }
 
    // Finally, try looking up relative to the config file path. Just like the
    // relative path passed to `require()` is found relative to the file it's
    // in, this allows plugin paths to be specified relative to the config file.
    const relativePath = path.resolve(configDir, plugin);
    try {
      return require.resolve(relativePath);
    } catch (requireError) {}
 
    throw new Error(errorString + ` and '${relativePath}')`);
  }
 
  /**
   * Get runtime configuration specified by the flags
   * @param {!Object} flags
   * @return {!Object} runtime config
   */
  static getRuntimeConfig(flags) {
    const emulationDesc = emulation.getEmulationDesc();
    const environment = [
      {
        name: 'Device Emulation',
        enabled: !flags.disableDeviceEmulation,
        description: emulationDesc['deviceEmulation']
      },
      {
        name: 'Network Throttling',
        enabled: !flags.disableNetworkThrottling,
        description: emulationDesc['networkThrottling']
      },
      {
        name: 'CPU Throttling',
        enabled: !flags.disableCpuThrottling,
        description: emulationDesc['cpuThrottling']
      }
    ];
 
    return {environment, blockedUrlPatterns: flags.blockedUrlPatterns || []};
  }
}
 
module.exports = Runner;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/aggregator/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/aggregator/

Statements: 1.69% (1 / 59)      Branches: 0% (0 / 32)      Functions: 0% (0 / 9)      Lines: 1.79% (1 / 56)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/aggregator/
File Statements Branches Functions Lines
aggregate.js 1.69% (1 / 59) 0% (0 / 32) 0% (0 / 9) 1.79% (1 / 56)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/aggregator/aggregate.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/aggregator/aggregate.js

Statements: 1.69% (1 / 59)      Branches: 0% (0 / 32)      Functions: 0% (0 / 9)      Lines: 1.79% (1 / 56)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224                                                                                                                                                                                                                                                                                                                                                                                                                                                          1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
class Aggregate {
 
  /**
   * @private
   * @param {!Array<!AuditResult>} results
   * @param {!AggregationCriteria} expected
   * @return {!Array<!AuditResult>}
   */
  static _filterResultsByAuditNames(results, expected) {
    const expectedNames = Object.keys(expected);
    return results.filter(r => expectedNames.includes(/** @type {string} */ (r.name)));
  }
 
  /**
   * @private
   * @param {!AggregationCriteria} expected
   * @return {number}
   */
  static _getTotalWeight(expected) {
    const expectedNames = Object.keys(expected);
    const totalWeight = expectedNames.reduce((last, e) => last + (expected[e].weight || 0), 0);
    return totalWeight;
  }
 
  /**
   * @private
   * @param {!Array<!AuditResult>} results
   * @return {!Object<!AuditResult>}
   */
  static _remapResultsByName(results) {
    const remapped = {};
    results.forEach(r => {
      if (remapped[r.name]) {
        throw new Error(`Cannot remap: ${r.name} already exists`);
      }
 
      remapped[r.name] = r;
    });
    return remapped;
  }
 
  /**
   * Converts each raw audit output to a weighted value for the aggregation.
   * @private
   * @param {!AuditResult} result The audit's output value.
   * @param {!AggregationCriterion} expected The aggregation's expected value and weighting for this result.
   * @param {!string} name The name of the audit.
   * @return {number} The weighted result.
   */
  static _convertToWeight(result, expected, name) {
    let weight = 0;
 
    if (typeof expected === 'undefined' ||
        typeof expected.expectedValue === 'undefined' ||
        typeof expected.weight === 'undefined') {
      const msg =
          `aggregations: ${name} audit does not contain expectedValue or weight properties`;
      throw new Error(msg);
    }
 
    // Audit resulted in an error, so doesn't contribute to score.
    // TODO: could do NaN instead, as score becomes somewhat meaningless.
    if (result.error) {
      return 0;
    }
 
    if (typeof result === 'undefined' ||
        typeof result.score === 'undefined') {
      let msg =
          `${name} audit result is undefined or does not contain score property`;
      if (result && result.debugString) {
        msg += ': ' + result.debugString;
      }
      throw new Error(msg);
    }
 
    if (typeof result.score !== typeof expected.expectedValue) {
      const expectedType = typeof expected.expectedValue;
      const resultType = typeof result.rawValue;
      let msg = `Expected expectedValue of type ${expectedType}, got ${resultType}`;
      if (result.debugString) {
        msg += ': ' + result.debugString;
      }
      throw new Error(msg);
    }
 
    switch (typeof expected.expectedValue) {
      case 'boolean':
        weight = this._convertBooleanToWeight(result.score,
            expected.expectedValue, expected.weight);
        break;
 
      case 'number':
        weight = this._convertNumberToWeight(result.score, expected.expectedValue, expected.weight);
        break;
 
      default:
        weight = 0;
        break;
    }
 
    return weight;
  }
 
  /**
   * Converts a numeric result to a weight.
   * @param {number} resultValue The result.
   * @param {number} expectedValue The expected value.
   * @param {number} weight The weight to assign.
   * @return {number} The final weight.
   */
  static _convertNumberToWeight(resultValue, expectedValue, weight) {
    return (resultValue / expectedValue) * weight;
  }
 
  /**
   * Converts a boolean result to a weight.
   * @param {boolean} resultValue The result.
   * @param {boolean} expectedValue The expected value.
   * @param {number} weight The weight to assign.
   * @return {number} The final weight.
   */
  static _convertBooleanToWeight(resultValue, expectedValue, weight) {
    return (resultValue === expectedValue) ? weight : 0;
  }
 
  /**
   * Compares the set of audit results to the expected values.
   * @param {!Array<!AuditResult>} results The audit results.
   * @param {!Array<!AggregationItem>} items The aggregation's expected values and weighting.
   * @return {!Array<!AggregationResultItem>} The aggregation score.
   */
  static compare(results, items) {
    return items.map(item => {
      const expectedNames = Object.keys(item.audits);
 
      // Filter down and remap the results to something more comparable to
      // the expected set of results.
      const filteredAndRemappedResults =
          Aggregate._remapResultsByName(
            Aggregate._filterResultsByAuditNames(results, item.audits)
          );
 
      const subItems = [];
      let overallScore = 0;
      let maxScore = 1;
 
      // Step through each item in the expected results, and add them
      // to the overall score and add each to the subItems list.
      expectedNames.forEach(e => {
        if (!filteredAndRemappedResults[e]) {
          throw new Error(`aggregations: expected audit results not found under audit name ${e}`);
        }
 
        subItems.push(filteredAndRemappedResults[e].name);
 
        overallScore += Aggregate._convertToWeight(
            filteredAndRemappedResults[e],
            item.audits[e],
            e);
      });
 
      maxScore = Aggregate._getTotalWeight(item.audits);
 
      return {
        overall: (overallScore / maxScore),
        name: item.name,
        description: item.description,
        subItems: subItems
      };
    });
  }
 
  /**
   * Calculates total score of an aggregate.
   * @param {!Array<!AggregationResultItem>} scores
   * @return {number}
   */
  static getTotal(scores) {
    return scores.reduce((total, s) => total + s.overall, 0) / scores.length;
  }
 
  /**
   * Aggregates all the results.
   * @param {!Aggregation} aggregation
   * @param {!Array<!AuditResult>} auditResults
   * @return {!AggregationResult}
   */
  static aggregate(aggregation, auditResults) {
    const score = Aggregate.compare(auditResults, aggregation.items);
    return {
      name: aggregation.name,
      description: aggregation.description,
      scored: aggregation.scored,
      additional: aggregation.additional,
      total: (aggregation.scored ? Aggregate.getTotal(score) : null),
      categorizable: aggregation.categorizable,
      score: score
    };
  }
}
 
module.exports = Aggregate;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/

Statements: 22.42% (74 / 330)      Branches: 0% (0 / 128)      Functions: 0% (0 / 61)      Lines: 22.77% (74 / 325)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/
File Statements Branches Functions Lines
audit.js 14.29% (2 / 14) 0% (0 / 10) 0% (0 / 4) 14.29% (2 / 14)
cache-start-url.js 14.29% (2 / 14) 0% (0 / 10) 0% (0 / 2) 14.29% (2 / 14)
content-width.js 20% (2 / 10) 0% (0 / 2) 0% (0 / 3) 20% (2 / 10)
critical-request-chains.js 21.05% (4 / 19) 0% (0 / 8) 0% (0 / 3) 21.05% (4 / 19)
deprecations.js 18.75% (3 / 16) 0% (0 / 8) 0% (0 / 2) 20% (3 / 15)
estimated-input-latency.js 31.58% (6 / 19) 100% (0 / 0) 0% (0 / 3) 33.33% (6 / 18)
first-meaningful-paint.js 20.69% (6 / 29) 0% (0 / 8) 0% (0 / 3) 21.43% (6 / 28)
is-on-https.js 50% (2 / 4) 100% (0 / 0) 0% (0 / 2) 50% (2 / 4)
manifest-background-color.js 33.33% (3 / 9) 0% (0 / 4) 0% (0 / 2) 33.33% (3 / 9)
manifest-display.js 15.38% (2 / 13) 0% (0 / 6) 0% (0 / 3) 15.38% (2 / 13)
manifest-exists.js 33.33% (2 / 6) 0% (0 / 2) 0% (0 / 2) 33.33% (2 / 6)
manifest-name.js 28.57% (2 / 7) 0% (0 / 4) 0% (0 / 2) 28.57% (2 / 7)
manifest-short-name-length.js 12.5% (2 / 16) 0% (0 / 10) 0% (0 / 2) 12.5% (2 / 16)
manifest-short-name.js 28.57% (2 / 7) 0% (0 / 6) 0% (0 / 2) 28.57% (2 / 7)
manifest-start-url.js 28.57% (2 / 7) 0% (0 / 4) 0% (0 / 2) 28.57% (2 / 7)
manifest-theme-color.js 28.57% (2 / 7) 0% (0 / 4) 0% (0 / 2) 28.57% (2 / 7)
redirects-http.js 50% (2 / 4) 100% (0 / 0) 0% (0 / 2) 50% (2 / 4)
screenshots.js 42.86% (3 / 7) 0% (0 / 2) 0% (0 / 2) 42.86% (3 / 7)
service-worker.js 40% (4 / 10) 0% (0 / 2) 0% (0 / 3) 44.44% (4 / 9)
theme-color-meta.js 30% (3 / 10) 0% (0 / 4) 0% (0 / 2) 30% (3 / 10)
time-to-interactive.js 17.39% (8 / 46) 0% (0 / 8) 0% (0 / 2) 17.39% (8 / 46)
user-timings.js 10.34% (3 / 29) 0% (0 / 16) 0% (0 / 5) 10.71% (3 / 28)
viewport.js 18.75% (3 / 16) 0% (0 / 8) 0% (0 / 2) 18.75% (3 / 16)
without-javascript.js 28.57% (2 / 7) 0% (0 / 2) 0% (0 / 2) 28.57% (2 / 7)
works-offline.js 50% (2 / 4) 100% (0 / 0) 0% (0 / 2) 50% (2 / 4)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/audit.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/audit.js

Statements: 14.29% (2 / 14)      Branches: 0% (0 / 10)      Functions: 0% (0 / 4)      Lines: 14.29% (2 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87                                    1                                                                                                                                   1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const DEFAULT_PASS = 'defaultPass';
 
class Audit {
  /**
   * @return {!string}
   */
  static get DEFAULT_PASS() {
    return DEFAULT_PASS;
  }
 
  /**
   * @throws {Error}
   */
  static get meta() {
    throw new Error('Audit meta information must be overridden.');
  }
 
  /**
   * @param {string} debugString
   * @return {!AuditResult}
   */
  static generateErrorAuditResult(debugString) {
    return this.generateAuditResult({
      rawValue: null,
      error: true,
      debugString
    });
  }
 
  /**
   * @param {!AuditResultInput} result
   * @return {!AuditResult}
   */
  static generateAuditResult(result) {
    if (typeof result.rawValue === 'undefined') {
      throw new Error('generateAuditResult requires a rawValue');
    }
 
    const score = typeof result.score === 'undefined' ? result.rawValue : result.score;
    let displayValue = result.displayValue;
    if (typeof displayValue === 'undefined') {
      displayValue = result.rawValue ? result.rawValue : '';
    }
 
    // The same value or true should be '' it doesn't add value to the report
    if (displayValue === score) {
      displayValue = '';
    }
 
    return {
      score,
      displayValue: `${displayValue}`,
      rawValue: result.rawValue,
      error: result.error,
      debugString: result.debugString,
      optimalValue: result.optimalValue,
      extendedInfo: result.extendedInfo,
      informative: this.meta.informative,
      name: this.meta.name,
      category: this.meta.category,
      description: this.meta.description,
      helpText: this.meta.helpText
    };
  }
}
 
module.exports = Audit;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/cache-start-url.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/cache-start-url.js

Statements: 14.29% (2 / 14)      Branches: 0% (0 / 10)      Functions: 0% (0 / 2)      Lines: 14.29% (2 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80                                      1                                                                                                                   1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
 
class CacheStartUrl extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Manifest',
      name: 'cache-start-url',
      description: 'Cache contains start_url from manifest (alpha)',
      requiredArtifacts: ['CacheContents', 'Manifest', 'URL']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    if (!artifacts.Manifest || !artifacts.Manifest.value) {
      // Page has no manifest or was invalid JSON.
      return CacheStartUrl.generateAuditResult({
        rawValue: false,
      });
    }
 
    const manifest = artifacts.Manifest.value;
    if (!(manifest.start_url && manifest.start_url.value)) {
      return CacheStartUrl.generateAuditResult({
        rawValue: false,
        debugString: 'start_url not present in Manifest'
      });
    }
 
    // Remove any UTM strings.
    const startURL = manifest.start_url.value;
    /** @const {string} */
    const altStartURL = startURL
        .replace(/\?utm_([^=]*)=([^&]|$)*/, '')
        .replace(/\?$/, '');
 
    // Now find the start_url in the cacheContents. This test is less than ideal since the Service
    // Worker can rewrite a request from the start URL to anything else in the cache, and so a TODO
    // here would be to resolve this more completely by asking the Service Worker about the start
    // URL. However that would also necessitate the cache contents gatherer relying on the manifest
    // gather rather than being independent of it.
    const cacheContents = artifacts.CacheContents;
    const cacheHasStartUrl = cacheContents.find(req => {
      return (startURL === req || altStartURL === req);
    });
 
    return CacheStartUrl.generateAuditResult({
      rawValue: (cacheHasStartUrl !== undefined)
    });
  }
}
 
module.exports = CacheStartUrl;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/content-width.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/content-width.js

Statements: 20% (2 / 10)      Branches: 0% (0 / 2)      Functions: 0% (0 / 3)      Lines: 20% (2 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                                      1                                                                                     1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
 
class ContentWidth extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Mobile Friendly',
      name: 'content-width',
      description: 'Content is sized correctly for the viewport',
      helpText: 'If the width of your app\'s content doesn\'t match the width ' +
          'of the viewport, your app might not be optimized for mobile screens. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/content-sized-correctly-for-viewport).',
      requiredArtifacts: ['ContentWidth']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    const scrollWidth = artifacts.ContentWidth.scrollWidth;
    const viewportWidth = artifacts.ContentWidth.viewportWidth;
    const widthsMatch = scrollWidth === viewportWidth;
 
    return ContentWidth.generateAuditResult({
      rawValue: widthsMatch,
      debugString: this.createDebugString(widthsMatch, artifacts.ContentWidth)
    });
  }
 
  static createDebugString(match, artifact) {
    if (match) {
      return '';
    }
 
    return 'The content scroll size is ' + artifact.scrollWidth + 'px, ' +
        'whereas the viewport size is ' + artifact.viewportWidth + 'px.';
  }
}
 
module.exports = ContentWidth;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/critical-request-chains.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/critical-request-chains.js

Statements: 21.05% (4 / 19)      Branches: 0% (0 / 8)      Functions: 0% (0 / 3)      Lines: 21.05% (4 / 19)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89                                      1 1                                                             1                                                                     1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
const Formatter = require('../formatters/formatter');
 
class CriticalRequestChains extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Performance',
      name: 'critical-request-chains',
      description: 'Critical Request Chains',
      informative: true,
      optimalValue: 0,
      helpText: 'The Critical Request Chains below show you what resources are ' +
          'required for first render of this page. Improve page load by reducing ' +
          'the length of chains, reducing the download size of resources, or ' +
          'deferring the download of unnecessary resources. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/critical-request-chains).',
      requiredArtifacts: ['networkRecords']
    };
  }
 
  /**
   * Audits the page to give a score for First Meaningful Paint.
   * @param {!Artifacts} artifacts The artifacts from the gather phase.
   * @return {!AuditResult} The score from the audit, ranging from 0-100.
   */
  static audit(artifacts) {
    const networkRecords = artifacts.networkRecords[Audit.DEFAULT_PASS];
    return artifacts.requestCriticalRequestChains(networkRecords).then(chains => {
      let chainCount = 0;
      function walk(node, depth) {
        const children = Object.keys(node);
 
        // Since a leaf node indicates the end of a chain, we can inspect the number
        // of child nodes, and, if the count is zero, increment the count.
        if (children.length === 0) {
          chainCount++;
        }
 
        children.forEach(id => {
          const child = node[id];
          walk(child.children, depth + 1);
        }, '');
      }
 
      // Account for initial navigation
      const initialNavKey = Object.keys(chains)[0];
      const initialNavChildren = initialNavKey && chains[initialNavKey].children;
      if (initialNavChildren && Object.keys(initialNavChildren).length > 0) {
        walk(initialNavChildren, 0);
      }
 
      return CriticalRequestChains.generateAuditResult({
        rawValue: chainCount <= this.meta.optimalValue,
        displayValue: chainCount,
        optimalValue: this.meta.optimalValue,
        extendedInfo: {
          formatter: Formatter.SUPPORTED_FORMATS.CRITICAL_REQUEST_CHAINS,
          value: chains
        }
      });
    });
  }
}
 
module.exports = CriticalRequestChains;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/deprecations.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/deprecations.js

Statements: 18.75% (3 / 16)      Branches: 0% (0 / 8)      Functions: 0% (0 / 2)      Lines: 20% (3 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82                                                1 1                                                                                                           1    
/**
 * @license
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
/**
 * @fileoverview Audits a page to determine if it is calling deprecated APIs.
 * This is done by collecting console log messages and filtering them by ones
 * that contain deprecated API warnings sent by Chrome.
 */
 
const Audit = require('./audit');
const Formatter = require('../formatters/formatter');
 
class Deprecations extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Deprecations',
      name: 'deprecations',
      description: 'Avoids deprecated APIs',
      helpText: 'Deprecated APIs will eventually be removed from the browser. ' +
          '[Learn more](https://www.chromestatus.com/features#deprecated).',
      requiredArtifacts: ['ChromeConsoleMessages']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    const entries = artifacts.ChromeConsoleMessages;
 
    const deprecations = entries.filter(log => log.entry.source === 'deprecation')
        .map(log => {
          // CSS deprecations can have missing URLs and lineNumbers. See https://crbug.com/680832.
          const label = log.entry.lineNumber ? `line: ${log.entry.lineNumber}` : 'line: ???';
          const url = log.entry.url || 'Unable to determine URL';
          return Object.assign({
            label,
            url,
            code: log.entry.text
          }, log.entry);
        });
 
    let displayValue = '';
    if (deprecations.length > 1) {
      displayValue = `${deprecations.length} warnings found`;
    } else if (deprecations.length === 1) {
      displayValue = `${deprecations.length} warning found`;
    }
 
    return Deprecations.generateAuditResult({
      rawValue: deprecations.length === 0,
      displayValue,
      extendedInfo: {
        formatter: Formatter.SUPPORTED_FORMATS.URLLIST,
        value: deprecations
      }
    });
  }
}
 
module.exports = Deprecations;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/estimated-input-latency.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/estimated-input-latency.js

Statements: 31.58% (6 / 19)      Branches: 100% (0 / 0)      Functions: 0% (0 / 3)      Lines: 33.33% (6 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97                                    1 1 1       1 1                                                                                                                                         1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const Audit = require('./audit');
const TracingProcessor = require('../lib/traces/tracing-processor');
const Formatter = require('../formatters/formatter');
 
// Parameters (in ms) for log-normal CDF scoring. To see the curve:
// https://www.desmos.com/calculator/srv0hqhf7d
const SCORING_POINT_OF_DIMINISHING_RETURNS = 50;
const SCORING_MEDIAN = 100;
 
class EstimatedInputLatency extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Performance',
      name: 'estimated-input-latency',
      description: 'Estimated Input Latency',
      optimalValue: SCORING_POINT_OF_DIMINISHING_RETURNS.toLocaleString() + 'ms',
      helpText: 'The score above is an estimate of how long your app takes to respond to user ' +
          'input, in milliseconds. There is a 90% probability that a user encounters this amount ' +
          'of latency, or less. 10% of the time a user can expect additional latency. If your ' +
          'score is higher than Lighthouse\'s target score, users may perceive your app as ' +
          'laggy. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/estimated-input-latency).',
      requiredArtifacts: ['traces']
    };
  }
 
  static calculate(speedline, model, trace) {
    // Use speedline's first paint as start of range for input latency check.
    const startTime = speedline.first;
 
    const latencyPercentiles = TracingProcessor.getRiskToResponsiveness(model, trace, startTime);
    const ninetieth = latencyPercentiles.find(result => result.percentile === 0.9);
    const rawValue = parseFloat(ninetieth.time.toFixed(1));
 
    // Use the CDF of a log-normal distribution for scoring.
    //  10th Percentile ≈ 58ms
    //  25th Percentile ≈ 75ms
    //  Median = 100ms
    //  75th Percentile ≈ 133ms
    //  95th Percentile ≈ 199ms
    const distribution = TracingProcessor.getLogNormalDistribution(SCORING_MEDIAN,
        SCORING_POINT_OF_DIMINISHING_RETURNS);
    const score = 100 * distribution.computeComplementaryPercentile(ninetieth.time);
 
    return EstimatedInputLatency.generateAuditResult({
      score: Math.round(score),
      optimalValue: this.meta.optimalValue,
      rawValue,
      displayValue: `${rawValue}ms`,
      extendedInfo: {
        value: latencyPercentiles,
        formatter: Formatter.SUPPORTED_FORMATS.NULL
      }
    });
  }
 
  /**
   * Audits the page to estimate input latency.
   * @see https://github.com/GoogleChrome/lighthouse/issues/28
   * @param {!Artifacts} artifacts The artifacts from the gather phase.
   * @return {!Promise<!AuditResult>} The score from the audit, ranging from 0-100.
   */
  static audit(artifacts) {
    const trace = artifacts.traces[this.DEFAULT_PASS];
 
    const pending = [
      artifacts.requestSpeedline(trace),
      artifacts.requestTracingModel(trace)
    ];
    return Promise.all(pending).then(([speedline, model]) =>
        EstimatedInputLatency.calculate(speedline, model, trace));
  }
}
 
module.exports = EstimatedInputLatency;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/first-meaningful-paint.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/first-meaningful-paint.js

Statements: 20.69% (6 / 29)      Branches: 0% (0 / 8)      Functions: 0% (0 / 3)      Lines: 21.43% (6 / 28)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134                                      1 1 1       1 1                                                                                                                                                                                                                 1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
const TracingProcessor = require('../lib/traces/tracing-processor');
const Formatter = require('../formatters/formatter');
 
// Parameters (in ms) for log-normal CDF scoring. To see the curve:
// https://www.desmos.com/calculator/joz3pqttdq
const SCORING_POINT_OF_DIMINISHING_RETURNS = 1600;
const SCORING_MEDIAN = 4000;
 
 
class FirstMeaningfulPaint extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Performance',
      name: 'first-meaningful-paint',
      description: 'First meaningful paint',
      optimalValue: SCORING_POINT_OF_DIMINISHING_RETURNS.toLocaleString() + 'ms',
      helpText: 'First meaningful paint measures when the primary content of a page is visible. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/first-meaningful-paint).',
      requiredArtifacts: ['traces']
    };
  }
 
  /**
   * Audits the page to give a score for First Meaningful Paint.
   * @see https://github.com/GoogleChrome/lighthouse/issues/26
   * @see https://docs.google.com/document/d/1BR94tJdZLsin5poeet0XoTW60M0SjvOJQttKT-JK8HI/view
   * @param {!Artifacts} artifacts The artifacts from the gather phase.
   * @return {!Promise<!AuditResult>} The score from the audit, ranging from 0-100.
   */
  static audit(artifacts) {
    const trace = artifacts.traces[this.DEFAULT_PASS];
    return artifacts.requestTraceOfTab(trace).then(tabTrace => {
      if (!tabTrace.firstMeaningfulPaintEvt) {
        throw new Error('No usable `firstMeaningfulPaint(Candidate)` events found in trace');
      }
 
      // navigationStart is currently essential to FMP calculation.
      // see: https://github.com/GoogleChrome/lighthouse/issues/753
      if (!tabTrace.navigationStartEvt) {
        throw new Error('No `navigationStart` event found in trace');
      }
 
      const result = this.calculateScore({
        navigationStart: tabTrace.navigationStartEvt,
        firstMeaningfulPaint: tabTrace.firstMeaningfulPaintEvt,
        firstContentfulPaint: tabTrace.firstContentfulPaintEvt
      });
 
      return FirstMeaningfulPaint.generateAuditResult({
        score: result.score,
        rawValue: parseFloat(result.duration),
        displayValue: `${result.duration}ms`,
        debugString: result.debugString,
        optimalValue: this.meta.optimalValue,
        extendedInfo: {
          value: result.extendedInfo,
          formatter: Formatter.SUPPORTED_FORMATS.NULL
        }
      });
    });
  }
 
  static calculateScore(evts) {
    const getTs = evt => evt && evt.ts;
    const getTiming = evt => {
      if (!evt) {
        return undefined;
      }
      const timing = (evt.ts - evts.navigationStart.ts) / 1000;
      return parseFloat(timing.toFixed(3));
    };
 
    // Expose the raw, unchanged monotonic timestamps from the trace, along with timing durations
    const extendedInfo = {
      timestamps: {
        navStart: getTs(evts.navigationStart),
        fCP: getTs(evts.firstContentfulPaint),
        fMP: getTs(evts.firstMeaningfulPaint)
      },
      timings: {
        navStart: 0,
        fCP: getTiming(evts.firstContentfulPaint),
        fMP: getTiming(evts.firstMeaningfulPaint)
      }
    };
 
    // Use the CDF of a log-normal distribution for scoring.
    //   < 1100ms: score≈100
    //   4000ms: score=50
    //   >= 14000ms: score≈0
    const firstMeaningfulPaint = getTiming(evts.firstMeaningfulPaint);
    const distribution = TracingProcessor.getLogNormalDistribution(SCORING_MEDIAN,
        SCORING_POINT_OF_DIMINISHING_RETURNS);
    let score = 100 * distribution.computeComplementaryPercentile(firstMeaningfulPaint);
 
    // Clamp the score to 0 <= x <= 100.
    score = Math.min(100, score);
    score = Math.max(0, score);
 
    return {
      duration: firstMeaningfulPaint.toFixed(1),
      score: Math.round(score),
      rawValue: firstMeaningfulPaint,
      extendedInfo
    };
  }
}
 
module.exports = FirstMeaningfulPaint;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/is-on-https.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/is-on-https.js

Statements: 50% (2 / 4)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 50% (2 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                                    1                                                               1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const Audit = require('./audit');
 
class HTTPS extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Security',
      name: 'is-on-https',
      description: 'Uses HTTPS',
      helpText: 'All sites should be protected with HTTPS, even ones that don\'t handle ' +
          'sensitive data. HTTPS prevents intruders from tampering with or passively listening ' +
          'in on the communications between your app and your users, and is a prerequisite for ' +
          'HTTP/2 and many new web platform APIs. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/https).',
      requiredArtifacts: ['HTTPS']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    return HTTPS.generateAuditResult({
      rawValue: artifacts.HTTPS.value,
      debugString: artifacts.HTTPS.debugString
    });
  }
}
 
module.exports = HTTPS;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-background-color.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-background-color.js

Statements: 33.33% (3 / 9)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 33.33% (3 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                                      1 1                                                                                     1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
const Formatter = require('../formatters/formatter');
 
class ManifestBackgroundColor extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Manifest',
      name: 'manifest-background-color',
      description: 'Manifest contains `background_color`',
      helpText: 'When your app launches from a user\'s homescreen, the browser ' +
          'uses `background_color` to paint the background of the browser ' +
          'while your app loads for a smooth transition experience. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/manifest-contains-background_color).',
      requiredArtifacts: ['Manifest']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    if (!artifacts.Manifest || !artifacts.Manifest.value) {
      // Page has no manifest or was invalid JSON.
      return ManifestBackgroundColor.generateAuditResult({
        rawValue: false,
      });
    }
 
    const manifest = artifacts.Manifest.value;
    const bgColor = manifest.background_color.value;
    return ManifestBackgroundColor.generateAuditResult({
      rawValue: !!bgColor,
      extendedInfo: {
        value: bgColor,
        formatter: Formatter.SUPPORTED_FORMATS.NULL
      }
    });
  }
}
 
module.exports = ManifestBackgroundColor;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-display.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-display.js

Statements: 15.38% (2 / 13)      Branches: 0% (0 / 6)      Functions: 0% (0 / 3)      Lines: 15.38% (2 / 13)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75                                      1                                                                                                         1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
 
class ManifestDisplay extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Manifest',
      name: 'manifest-display',
      description: 'Manifest\'s `display` property is set',
      helpText: 'Set the `display` property to specify how your app ' +
          'launches from the homescreen. [Learn ' +
          'more](https://developers.google.com/web/tools/lighthouse/audits/manifest-has-display-set).',
      requiredArtifacts: ['Manifest']
    };
  }
 
  /**
   * @param {string|undefined} val
   * @return {boolean}
   */
  static hasRecommendedValue(val) {
    return ['browser', 'fullscreen', 'minimal-ui', 'standalone'].includes(val);
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    if (!artifacts.Manifest || !artifacts.Manifest.value) {
      // Page has no manifest or was invalid JSON.
      return ManifestDisplay.generateAuditResult({
        rawValue: false
      });
    }
 
    const manifest = artifacts.Manifest.value;
    const displayValue = manifest.display.value;
    const hasRecommendedValue = ManifestDisplay.hasRecommendedValue(displayValue);
 
    const auditResult = {
      rawValue: hasRecommendedValue,
      displayValue
    };
    if (!hasRecommendedValue) {
      auditResult.debugString = 'Manifest display property should be set.';
    }
    return ManifestDisplay.generateAuditResult(auditResult);
  }
}
 
module.exports = ManifestDisplay;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-exists.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-exists.js

Statements: 33.33% (2 / 6)      Branches: 0% (0 / 2)      Functions: 0% (0 / 2)      Lines: 33.33% (2 / 6)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                                      1                                                                         1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
 
class ManifestExists extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Manifest',
      name: 'manifest-exists',
      description: 'Manifest exists',
      helpText: 'The web app manifest is the technology that enables users ' +
          'to add your web app to their homescreen. [Learn ' +
          'more](https://developers.google.com/web/tools/lighthouse/audits/manifest-exists).',
      requiredArtifacts: ['Manifest']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    if (!artifacts.Manifest) {
      // Page has no manifest.
      return ManifestExists.generateAuditResult({
        rawValue: false
      });
    }
 
    return ManifestExists.generateAuditResult({
      rawValue: typeof artifacts.Manifest.value !== 'undefined',
      debugString: artifacts.Manifest.debugString
    });
  }
}
 
module.exports = ManifestExists;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-name.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-name.js

Statements: 28.57% (2 / 7)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 28.57% (2 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                                      1                                                                       1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
 
class ManifestName extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Manifest',
      name: 'manifest-name',
      description: 'Manifest contains `name`',
      helpText: 'The `name` property identifies your app and is required. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/manifest-contains-name).',
      requiredArtifacts: ['Manifest']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    if (!artifacts.Manifest || !artifacts.Manifest.value) {
      // Page has no manifest or was invalid JSON.
      return ManifestName.generateAuditResult({
        rawValue: false
      });
    }
 
    const manifest = artifacts.Manifest.value;
    return ManifestName.generateAuditResult({
      rawValue: !!manifest.name.value
    });
  }
}
 
module.exports = ManifestName;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-short-name-length.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-short-name-length.js

Statements: 12.5% (2 / 16)      Branches: 0% (0 / 10)      Functions: 0% (0 / 2)      Lines: 12.5% (2 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82                                      1                                                                                                                       1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
 
class ManifestShortNameLength extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Manifest',
      name: 'manifest-short-name-length',
      description: 'Manifest\'s `short_name` won\'t be truncated when displayed on homescreen',
      helpText: 'Make your app\'s `short_name` less than 12 characters to ' +
          'ensure that it\'s not truncated on homescreens. [Learn ' +
          'more](https://developers.google.com/web/tools/lighthouse/audits/manifest-short_name-is-not-truncated).',
      requiredArtifacts: ['Manifest']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    if (!artifacts.Manifest || !artifacts.Manifest.value) {
      // Page has no manifest or was invalid JSON.
      return ManifestShortNameLength.generateAuditResult({
        rawValue: false
      });
    }
 
    // When no shortname can be found we look for a name.
    const manifest = artifacts.Manifest.value;
    const shortNameValue = manifest.short_name.value || manifest.name.value;
 
    if (!shortNameValue) {
      return ManifestShortNameLength.generateAuditResult({
        rawValue: false,
        debugString: 'No short_name found in manifest.'
      });
    }
 
    // Historically, Chrome recommended 12 chars as the maximum length to prevent truncation.
    // See #69 for more discussion.
    // https://developer.chrome.com/apps/manifest/name#short_name
    const suggestedLength = 12;
    const isShortNameShortEnough = shortNameValue.length <= suggestedLength;
 
    let debugString;
    if (!isShortNameShortEnough) {
      debugString = `${suggestedLength} chars is the suggested maximum homescreen label length`;
      debugString += ` (Found: ${shortNameValue.length} chars).`;
    }
 
    return ManifestShortNameLength.generateAuditResult({
      rawValue: isShortNameShortEnough,
      debugString
    });
  }
}
 
module.exports = ManifestShortNameLength;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-short-name.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-short-name.js

Statements: 28.57% (2 / 7)      Branches: 0% (0 / 6)      Functions: 0% (0 / 2)      Lines: 28.57% (2 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                                      1                                                                           1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
 
class ManifestShortName extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Manifest',
      name: 'manifest-short-name',
      description: 'Manifest contains `short_name`',
      helpText: 'The `short_name` property is a requirement for Add ' +
          'To Homescreen. [Learn ' +
          'more](https://developers.google.com/web/tools/lighthouse/audits/manifest-contains-short_name).',
      requiredArtifacts: ['Manifest']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    if (!artifacts.Manifest || !artifacts.Manifest.value) {
      // Page has no manifest or was invalid JSON.
      return ManifestShortName.generateAuditResult({
        rawValue: false
      });
    }
 
    const manifest = artifacts.Manifest.value;
    return ManifestShortName.generateAuditResult({
      // When no shortname can be found we look for a name.
      rawValue: !!(manifest.short_name.value || manifest.name.value)
    });
  }
}
 
module.exports = ManifestShortName;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-start-url.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-start-url.js

Statements: 28.57% (2 / 7)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 28.57% (2 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                                      1                                                                         1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
 
class ManifestStartUrl extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Manifest',
      name: 'manifest-start-url',
      description: 'Manifest contains `start_url`',
      helpText: 'Add a `start_url` to instruct the browser to launch a ' +
          'specific URL whenever your app is launched from a homescreen. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/manifest-contains-start_url).',
      requiredArtifacts: ['Manifest']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    if (!artifacts.Manifest || !artifacts.Manifest.value) {
      // Page has no manifest or was invalid JSON.
      return ManifestStartUrl.generateAuditResult({
        rawValue: false
      });
    }
 
    const manifest = artifacts.Manifest.value;
    return ManifestStartUrl.generateAuditResult({
      rawValue: !!manifest.start_url.value
    });
  }
}
 
module.exports = ManifestStartUrl;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-theme-color.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/manifest-theme-color.js

Statements: 28.57% (2 / 7)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 28.57% (2 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                                      1                                                                         1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
 
class ManifestThemeColor extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Manifest',
      name: 'manifest-theme-color',
      description: 'Manifest contains `theme_color`',
      helpText: 'Add a `theme_color` to set the color of the browser\'s ' +
          'address bar. [Learn ' +
          'more](https://developers.google.com/web/tools/lighthouse/audits/manifest-contains-theme_color).',
      requiredArtifacts: ['Manifest']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    if (!artifacts.Manifest || !artifacts.Manifest.value) {
      // Page has no manifest or was invalid JSON.
      return ManifestThemeColor.generateAuditResult({
        rawValue: false
      });
    }
 
    const manifest = artifacts.Manifest.value;
    return ManifestThemeColor.generateAuditResult({
      rawValue: !!manifest.theme_color.value
    });
  }
}
 
module.exports = ManifestThemeColor;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/redirects-http.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/redirects-http.js

Statements: 50% (2 / 4)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 50% (2 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50                                    1                                                         1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const Audit = require('./audit');
 
class RedirectsHTTP extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Security',
      name: 'redirects-http',
      description: 'Redirects HTTP traffic to HTTPS',
      helpText: 'If you\'ve already set up HTTPS, make sure that you redirect all HTTP traffic ' +
         'to HTTPS. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/http-redirects-to-https).',
      requiredArtifacts: ['HTTPRedirect']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    return RedirectsHTTP.generateAuditResult({
      rawValue: artifacts.HTTPRedirect.value,
      debugString: artifacts.HTTPRedirect.debugString
    });
  }
}
 
module.exports = RedirectsHTTP;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/screenshots.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/screenshots.js

Statements: 42.86% (3 / 7)      Branches: 0% (0 / 2)      Functions: 0% (0 / 2)      Lines: 42.86% (3 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57                                      1 1                                                                   1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
const Formatter = require('../formatters/formatter');
 
class Screenshots extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Performance',
      name: 'screenshots',
      description: 'Screenshots of all captured frames',
      requiredArtifacts: ['traces']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!Promise<!AuditResult>}
   */
  static audit(artifacts) {
    const trace = artifacts.traces[this.DEFAULT_PASS];
 
    return artifacts.requestScreenshots(trace).then(screenshots => {
      return Screenshots.generateAuditResult({
        rawValue: screenshots.length || 0,
        extendedInfo: {
          formatter: Formatter.SUPPORTED_FORMATS.NULL,
          value: screenshots
        }
      });
    });
  }
}
 
module.exports = Screenshots;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/service-worker.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/service-worker.js

Statements: 40% (4 / 10)      Branches: 0% (0 / 2)      Functions: 0% (0 / 3)      Lines: 44.44% (4 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                                      1 1             1                                                                         1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const URL = require('../lib/url-shim');
const Audit = require('./audit');
 
/**
 * @param {!Array<!ServiceWorkerVersion>} versions
 * @param {string} url
 * @return {(!ServiceWorkerVersion|undefined)}
 */
function getActivatedServiceWorker(versions, url) {
  const origin = new URL(url).origin;
  return versions.find(v => v.status === 'activated' && new URL(v.scriptURL).origin === origin);
}
 
class ServiceWorker extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Offline',
      name: 'service-worker',
      description: 'Registers a Service Worker',
      helpText: 'The service worker is the technology that enables your app to use many ' +
         'Progressive Web App features, such as offline, add to homescreen, and push ' +
         'notifications. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/registered-service-worker).',
      requiredArtifacts: ['URL', 'ServiceWorker']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    // Find active service worker for this URL. Match against
    // artifacts.URL.finalUrl so audit accounts for any redirects.
    const version = getActivatedServiceWorker(
        artifacts.ServiceWorker.versions, artifacts.URL.finalUrl);
 
    return ServiceWorker.generateAuditResult({
      rawValue: !!version
    });
  }
}
 
module.exports = ServiceWorker;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/theme-color-meta.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/theme-color-meta.js

Statements: 30% (3 / 10)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 30% (3 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64                                    1 1                                                                                   1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const validColor = require('../lib/web-inspector').Color.parse;
const Audit = require('./audit');
 
class ThemeColor extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'HTML',
      name: 'theme-color-meta',
      description: 'Has a `<meta name="theme-color">` tag',
      requiredArtifacts: ['ThemeColor']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    const themeColorMeta = artifacts.ThemeColor;
    if (themeColorMeta === null) {
      return ThemeColor.generateAuditResult({
        rawValue: false
      });
    }
 
    if (!validColor(themeColorMeta)) {
      return ThemeColor.generateAuditResult({
        displayValue: themeColorMeta,
        rawValue: false,
        debugString: 'The theme-color meta tag did not contain a valid CSS color.'
      });
    }
 
    return ThemeColor.generateAuditResult({
      displayValue: themeColorMeta,
      rawValue: true
    });
  }
}
 
module.exports = ThemeColor;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/time-to-interactive.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/time-to-interactive.js

Statements: 17.39% (8 / 46)      Branches: 0% (0 / 8)      Functions: 0% (0 / 2)      Lines: 17.39% (8 / 46)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170                    1 1 1 1       1 1   1                                                                                                                                                                                                                                                                                                     1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
const TracingProcessor = require('../lib/traces/tracing-processor');
const FMPMetric = require('./first-meaningful-paint');
const Formatter = require('../formatters/formatter');
 
// Parameters (in ms) for log-normal CDF scoring. To see the curve:
//   https://www.desmos.com/calculator/jlrx14q4w8
const SCORING_POINT_OF_DIMINISHING_RETURNS = 1700;
const SCORING_MEDIAN = 5000;
// This aligns with the external TTI targets in https://goo.gl/yXqxpL
const SCORING_TARGET = 5000;
 
class TTIMetric extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Performance',
      name: 'time-to-interactive',
      description: 'Time To Interactive (alpha)',
      helpText: 'Time to Interactive identifies the time at which your app appears to be ready ' +
          'enough to interact with. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/time-to-interactive).',
      optimalValue: SCORING_TARGET.toLocaleString() + 'ms',
      requiredArtifacts: ['traces']
    };
  }
 
  /**
   * Identify the time the page is "interactive"
   * @see https://docs.google.com/document/d/1oiy0_ych1v2ADhyG_QW7Ps4BNER2ShlJjx2zCbVzVyY/edit#
   *
   * The user thinks the page is ready - (They believe the page is done enough to start interacting with)
   *   - Layout has stabilized & key webfonts are visible.
   *     AKA: First meaningful paint has fired.
   *   - Page is nearly visually complete
   *     Visual completion is 85%
   *
   * The page is actually ready for user:
   *   - domContentLoadedEventEnd has fired
   *     Definition: HTML parsing has finished, all DOMContentLoaded handlers have run.
   *     No risk of DCL event handlers changing the page
   *     No surprises of inactive buttons/actions as DOM element event handlers should be bound
   *   - The main thread is available enough to handle user input
   *     first 500ms window where Est Input Latency is <50ms at the 90% percentile.
   *
   * WARNING: This metric WILL change its calculation. If you rely on its numbers now, know that they
   * will be changing in the future to a more accurate number.
   *
   * @param {!Artifacts} artifacts The artifacts from the gather phase.
   * @return {!Promise<!AuditResult>} The score from the audit, ranging from 0-100.
   */
  static audit(artifacts) {
    const trace = artifacts.traces[Audit.DEFAULT_PASS];
 
    // We start looking at Math.Max(FMPMetric, visProgress[0.85])
    const pending = [
      artifacts.requestSpeedline(trace),
      FMPMetric.audit(artifacts),
      artifacts.requestTracingModel(trace)
    ];
    return Promise.all(pending).then(([speedline, fmpResult, model]) => {
      const endOfTraceTime = model.bounds.max;
      const fmpTiming = fmpResult.rawValue;
      const fmpResultExt = fmpResult.extendedInfo.value;
 
      // frame monotonic timestamps from speedline are in ms (ts / 1000), so we'll match
      //   https://github.com/pmdartus/speedline/blob/123f512632a/src/frame.js#L86
      const fMPtsInMS = fmpResultExt.timestamps.fMP / 1000;
      const navStartTsInMS = fmpResultExt.timestamps.navStart / 1000;
 
      // look at speedline results for 85% starting at FMP
      let visuallyReadyTiming = 0;
      if (speedline.frames) {
        const eightyFivePctVC = speedline.frames.find(frame => {
          return frame.getTimeStamp() >= fMPtsInMS && frame.getProgress() >= 85;
        });
        if (eightyFivePctVC) {
          visuallyReadyTiming = eightyFivePctVC.getTimeStamp() - navStartTsInMS;
        }
      }
 
      // Find first 500ms window where Est Input Latency is <50ms at the 90% percentile.
      let startTime = Math.max(fmpTiming, visuallyReadyTiming) - 50;
      let endTime;
      let currentLatency = Infinity;
      const percentiles = [0.9]; // [0.75, 0.9, 0.99, 1];
      const threshold = 50;
      const foundLatencies = [];
 
      // When we've found a latency that's good enough, we're good.
      while (currentLatency > threshold) {
        // While latency is too high, increment just 50ms and look again.
        startTime += 50;
        endTime = startTime + 500;
        // If there's no more room in the trace to look, we're done.
        if (endTime > endOfTraceTime) {
          throw new Error('Entire trace was found to be busy.');
        }
        // Get our expected latency for the time window
        const latencies = TracingProcessor.getRiskToResponsiveness(
          model, trace, startTime, endTime, percentiles);
        const estLatency = latencies[0].time;
        foundLatencies.push({
          estLatency: estLatency,
          startTime: startTime.toFixed(1)
        });
 
        // Grab this latency and try the threshold again
        currentLatency = estLatency;
      }
      // The start of our window is our TTI
      const timeToInteractive = startTime;
 
      // Use the CDF of a log-normal distribution for scoring.
      //   < 1200ms: score≈100
      //   5000ms: score=50
      //   >= 15000ms: score≈0
      const distribution = TracingProcessor.getLogNormalDistribution(SCORING_MEDIAN,
          SCORING_POINT_OF_DIMINISHING_RETURNS);
      let score = 100 * distribution.computeComplementaryPercentile(startTime);
 
      // Clamp the score to 0 <= x <= 100.
      score = Math.min(100, score);
      score = Math.max(0, score);
      score = Math.round(score);
 
      const extendedInfo = {
        timings: {
          fMP: parseFloat(fmpTiming.toFixed(3)),
          visuallyReady: parseFloat(visuallyReadyTiming.toFixed(3)),
          timeToInteractive: parseFloat(startTime.toFixed(3))
        },
        timestamps: {
          fMP: fMPtsInMS * 1000,
          visuallyReady: (visuallyReadyTiming + navStartTsInMS) * 1000,
          timeToInteractive: (timeToInteractive + navStartTsInMS) * 1000
        },
        expectedLatencyAtTTI: parseFloat(currentLatency.toFixed(3)),
        foundLatencies
      };
 
      return TTIMetric.generateAuditResult({
        score,
        rawValue: parseFloat(timeToInteractive.toFixed(1)),
        displayValue: `${parseFloat(timeToInteractive.toFixed(1))}ms`,
        optimalValue: this.meta.optimalValue,
        extendedInfo: {
          value: extendedInfo,
          formatter: Formatter.SUPPORTED_FORMATS.NULL
        }
      });
    });
  }
}
 
module.exports = TTIMetric;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/user-timings.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/user-timings.js

Statements: 10.34% (3 / 29)      Branches: 0% (0 / 16)      Functions: 0% (0 / 5)      Lines: 10.71% (3 / 28)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141                                      1 1                                                                                                                                                                                                                                           1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
const Formatter = require('../formatters/formatter');
 
class UserTimings extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Performance',
      name: 'user-timings',
      description: 'User Timing marks and measures',
      helpText: 'Consider instrumenting your app with the User Timing API to create custom, ' +
          'real-world measurements of key user experiences. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/user-timing).',
      requiredArtifacts: ['traces'],
      informative: true
    };
  }
 
  /**
   * @param {!Object} tabTrace
   * @return {!Array<!UserTimingsExtendedInfo>}
   */
  static filterTrace(tabTrace) {
    const userTimings = [];
    const measuresStartTimes = {};
 
    // Get all blink.user_timing events
    // The event phases we are interested in are mark and instant events (R, i, I)
    // and duration events which correspond to measures (B, b, E, e).
    // @see https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#
    tabTrace.processEvents.filter(evt => {
      if (!evt.cat.includes('blink.user_timing')) {
        return false;
      }
 
      // reject these "userTiming" events that aren't really UserTiming, by nuking ones with frame data (or requestStart)
      // https://cs.chromium.org/search/?q=trace_event.*?user_timing&sq=package:chromium&type=cs
      return evt.name !== 'requestStart' &&
          evt.name !== 'navigationStart' &&
          evt.name !== 'paintNonDefaultBackgroundColor' &&
          evt.args.frame === undefined;
    })
    .forEach(ut => {
      // Mark events fall under phases R and I (or i)
      if (ut.ph === 'R' || ut.ph.toUpperCase() === 'I') {
        userTimings.push({
          name: ut.name,
          isMark: true,
          args: ut.args,
          startTime: ut.ts
        });
 
      // Beginning of measure event, keep track of this events start time
      } else if (ut.ph.toLowerCase() === 'b') {
        measuresStartTimes[ut.name] = ut.ts;
 
      // End of measure event
      } else if (ut.ph.toLowerCase() === 'e') {
        userTimings.push({
          name: ut.name,
          isMark: false,
          args: ut.args,
          startTime: measuresStartTimes[ut.name],
          endTime: ut.ts
        });
      }
    });
 
    // baseline the timestamps against navStart, and translate to milliseconds
    userTimings.forEach(ut => {
      ut.startTime = (ut.startTime - tabTrace.navigationStartEvt.ts) / 1000;
      if (!ut.isMark) {
        ut.endTime = (ut.endTime - tabTrace.navigationStartEvt.ts) / 1000;
        ut.duration = ut.endTime - ut.startTime;
      }
    });
 
    return userTimings;
  }
 
  /*
   * @return {!Array<string>}
   */
  static get blacklistedPrefixes() {
    return ['goog_'];
  }
 
  /**
   * We remove mark/measures entered by third parties not of interest to the user
   * @param {!UserTimingsExtendedInfo} artifacts
   * @return {boolean}
   */
  static excludeBlacklisted(timing) {
    return UserTimings.blacklistedPrefixes.every(prefix => !timing.name.startsWith(prefix));
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    const trace = artifacts.traces[Audit.DEFAULT_PASS];
    return artifacts.requestTraceOfTab(trace).then(tabTrace => {
      const userTimings = this.filterTrace(tabTrace).filter(UserTimings.excludeBlacklisted);
 
      return UserTimings.generateAuditResult({
        rawValue: true,
        displayValue: userTimings.length,
        extendedInfo: {
          formatter: Formatter.SUPPORTED_FORMATS.USER_TIMINGS,
          value: userTimings
        }
      });
    });
  }
}
 
module.exports = UserTimings;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/viewport.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/viewport.js

Statements: 18.75% (3 / 16)      Branches: 0% (0 / 8)      Functions: 0% (0 / 2)      Lines: 18.75% (3 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72                                    1 1                                                                                                   1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const Audit = require('./audit');
const Parser = require('metaviewport-parser');
 
class Viewport extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Mobile Friendly',
      name: 'viewport',
      description: 'Has a `<meta name="viewport">` tag with `width` or `initial-scale`',
      helpText: 'Add a viewport meta tag to optimize your app for mobile screens. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/has-viewport-meta-tag).',
      requiredArtifacts: ['Viewport']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    if (artifacts.Viewport === null) {
      return Viewport.generateAuditResult({
        debugString: 'No viewport meta tag found',
        rawValue: false
      });
    }
 
    let debugString = '';
    const parsedProps = Parser.parseMetaViewPortContent(artifacts.Viewport);
 
    if (Object.keys(parsedProps.unknownProperties).length) {
      debugString += `Invalid properties found: ${JSON.stringify(parsedProps.unknownProperties)}. `;
    }
    if (Object.keys(parsedProps.invalidValues).length) {
      debugString += `Invalid values found: ${JSON.stringify(parsedProps.invalidValues)}. `;
    }
    debugString = debugString.trim();
 
    const viewportProps = parsedProps.validProperties;
    const hasMobileViewport = viewportProps.width || viewportProps['initial-scale'];
 
    return Viewport.generateAuditResult({
      rawValue: !!hasMobileViewport,
      debugString
    });
  }
}
 
module.exports = Viewport;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/without-javascript.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/without-javascript.js

Statements: 28.57% (2 / 7)      Branches: 0% (0 / 2)      Functions: 0% (0 / 2)      Lines: 28.57% (2 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                                      1                                                                           1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Audit = require('./audit');
 
class WithoutJavaScript extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'JavaScript',
      name: 'without-javascript',
      description: 'Contains some content when JavaScript is not available',
      helpText: 'Your app should display some content when JavaScript is disabled, even if it\'s ' +
          'just a warning to the user that JavaScript is required to use the app. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/no-js).',
      requiredArtifacts: ['HTMLWithoutJavaScript']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    const artifact = artifacts.HTMLWithoutJavaScript;
 
    if (artifact.value.trim() === '') {
      return WithoutJavaScript.generateAuditResult({
        rawValue: false,
        debugString: 'The page body should render some content if its scripts are not available.'
      });
    }
 
    return WithoutJavaScript.generateAuditResult({
      rawValue: true
    });
  }
}
 
module.exports = WithoutJavaScript;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/works-offline.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/audits/works-offline.js

Statements: 50% (2 / 4)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 50% (2 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50                                    1                                                         1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const Audit = require('./audit');
 
class WorksOffline extends Audit {
  /**
   * @return {!AuditMeta}
   */
  static get meta() {
    return {
      category: 'Offline',
      name: 'works-offline',
      description: 'Responds with a 200 when offline',
      helpText: 'If you\'re building a Progressive Web App, consider using a service worker so ' +
          'that your app can work offline. ' +
          '[Learn more](https://developers.google.com/web/tools/lighthouse/audits/http-200-when-offline).',
      requiredArtifacts: ['Offline']
    };
  }
 
  /**
   * @param {!Artifacts} artifacts
   * @return {!AuditResult}
   */
  static audit(artifacts) {
    return WorksOffline.generateAuditResult({
      rawValue: artifacts.Offline === 200
    });
  }
}
 
module.exports = WorksOffline;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/closure/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/closure/

Statements: 10% (1 / 10)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 10% (1 / 10)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/closure/
File Statements Branches Functions Lines
closure-type-checking.js 10% (1 / 10) 0% (0 / 2) 0% (0 / 1) 10% (1 / 10)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/closure/closure-type-checking.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/closure/closure-type-checking.js

Statements: 10% (1 / 10)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 10% (1 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90                                      2                                                                                                                                            
//#!/usr/bin/env node
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const closureCompiler = require('google-closure-compiler').gulp();
const gulp = require('gulp');
const gutil = require('gulp-util');
const replace = require('gulp-replace');
 
/* eslint-disable camelcase */
gulp.task('js-compile', function() {
  return gulp.src([
    'closure/typedefs/*.js',
    'closure/third_party/*.js',
    'audits/**/*.js',
    'lib/event-helpers.js',
    'lib/icons.js',
    'lib/styles-helpers.js',
    'lib/url-shim.js',
    'aggregator/**/*.js'
  ])
    // Hack to remove `require`s that Closure currently can't resolve.
    .pipe(replace('require(\'../lib/web-inspector\').Color.parse;',
        'WebInspector.Color.parse;'))
    .pipe(replace('require(\'../lib/traces/tracing-processor\');', '/** @type {?} */ (null);'))
    .pipe(replace('require(\'../lib/traces/devtools-timeline-model\');',
        'DevtoolsTimelineModel'))
    .pipe(replace('require(\'speedline\');', 'function(arg) {};'))
    .pipe(replace(/require\('(\.\.\/)*formatters\/formatter'\);/g, '{};'))
 
    // Replace any non-local import (e.g. not starting with .) with a dummy type. These are likely
    // the built-in Node modules. But not always, so TODO(samthor): Fix this.
    .pipe(replace(/require\(\'[^\.].*?\'\)/g, '/** @type {*} */ ({})'))
 
    .pipe(closureCompiler({
      compilation_level: 'SIMPLE',
      process_common_js_modules: true,
      new_type_inf: true,
      checks_only: true,
      language_in: 'ECMASCRIPT6_STRICT',
      language_out: 'ECMASCRIPT5_STRICT',
      warning_level: process.env.CI ? 'QUIET' : 'VERBOSE',
      jscomp_error: [
        'checkTypes',
        'conformanceViolations'
      ],
      jscomp_warning: [
        // https://github.com/google/closure-compiler/wiki/Warnings
        'accessControls',
        'checkRegExp',
        'const',
        // 'reportUnknownTypes',
        'missingProperties',
        'missingReturn',
        'newCheckTypes',
        'strictModuleDepCheck',
        'typeInvalidation',
        'undefinedNames',
        'visibility'
      ],
      conformance_configs: 'closure/conformance_config.textproto'
    }))
    .on('error', error => {
      gutil.log('Closure compilation failed. Check `closure-error.log` for details.');
      require('fs').writeFileSync('closure-error.log', error);
    })
    .on('end', () => {
      gutil.log('Closure compilation successful.');
    });
});
/* eslint-enable */
 
gulp.start('js-compile');
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/config/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/config/

Statements: 9.14% (16 / 175)      Branches: 0% (0 / 103)      Functions: 0% (0 / 16)      Lines: 9.47% (16 / 169)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/config/
File Statements Branches Functions Lines
config.js 9.14% (16 / 175) 0% (0 / 103) 0% (0 / 16) 9.47% (16 / 169)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/config/config.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/config/config.js

Statements: 9.14% (16 / 175)      Branches: 0% (0 / 103)      Functions: 0% (0 / 16)      Lines: 9.47% (16 / 169)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402                                    1 1 1   1 1 1 1 1           1                                                                                                                                                             1                                                                   1                         1                                                                     1                                                                                   1                                 1                                                                                                                                                                                                                                                                                                     1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const defaultConfigPath = './default.json';
const defaultConfig = require('./default.json');
const recordsFromLogs = require('../lib/network-recorder').recordsFromLogs;
 
const GatherRunner = require('../gather/gather-runner');
const log = require('../lib/log');
const path = require('path');
const Audit = require('../audits/audit');
const Runner = require('../runner');
 
// cleanTrace is run to remove duplicate TracingStartedInPage events,
// and to change TracingStartedInBrowser events into TracingStartedInPage.
// This is done by searching for most occuring threads and basing new events
// off of those.
function cleanTrace(trace) {
  const traceEvents = trace.traceEvents;
  // Keep track of most occuring threads
  const threads = [];
  const countsByThread = {};
  const traceStartEvents = [];
  const makeMockEvent = (evt, ts) => {
    return {
      pid: evt.pid,
      tid: evt.tid,
      ts: ts || 0,  // default to 0 for now
      ph: 'I',
      cat: 'disabled-by-default-devtools.timeline',
      name: 'TracingStartedInPage',
      args: {
        data: {
          page: evt.frame
        }
      },
      s: 't'
    };
  };
 
  let frame;
  let data;
  let name;
  let counter;
 
  traceEvents.forEach((evt, idx) => {
    if (evt.name.startsWith('TracingStartedIn')) {
      traceStartEvents.push(idx);
    }
 
    // find the event's frame
    data = evt.args && (evt.args.data || evt.args.beginData || evt.args.counters);
    frame = (evt.args && evt.args.frame) || data && (data.frame || data.page);
 
    if (!frame) {
      return;
    }
 
    // Increase occurences count of the frame
    name = `pid${evt.pid}-tid${evt.tid}-frame${frame}`;
    counter = countsByThread[name];
    if (!counter) {
      counter = {
        pid: evt.pid,
        tid: evt.tid,
        frame: frame,
        count: 0
      };
      countsByThread[name] = counter;
      threads.push(counter);
    }
    counter.count++;
  });
 
  // find most active thread (and frame)
  threads.sort((a, b) => b.count - a.count);
  const mostActiveFrame = threads[0];
 
  // Remove all current TracingStartedIn* events, storing
  // the first events ts.
  const ts = traceEvents[traceStartEvents[0]] && traceEvents[traceStartEvents[0]].ts;
 
  // account for offset after removing items
  let i = 0;
  for (const dup of traceStartEvents) {
    traceEvents.splice(dup - i, 1);
    i++;
  }
 
  // Add a new TracingStartedInPage event based on most active thread
  // and using TS of first found TracingStartedIn* event
  traceEvents.unshift(makeMockEvent(mostActiveFrame, ts));
 
  return trace;
}
 
function validatePasses(passes, audits, rootPath) {
  if (!Array.isArray(passes)) {
    return;
  }
  const requiredGatherers = getGatherersNeededByAudits(audits);
 
  // Log if we are running gathers that are not needed by the audits listed in the config
  passes.forEach(pass => {
    pass.gatherers.forEach(gatherer => {
      const GathererClass = GatherRunner.getGathererClass(gatherer, rootPath);
      const isGatherRequiredByAudits = requiredGatherers.has(GathererClass.name);
      if (isGatherRequiredByAudits === false) {
        const msg = `${GathererClass.name} gatherer requested, however no audit requires it.`;
        log.warn('config', msg);
      }
    });
  });
 
  // Log if multiple passes require trace or network recording and could overwrite one another.
  const usedNames = new Set();
  passes.forEach((pass, index) => {
    if (!pass.recordNetwork && !pass.recordTrace) {
      return;
    }
 
    const passName = pass.passName || Audit.DEFAULT_PASS;
    if (usedNames.has(passName)) {
      log.warn('config', `passes[${index}] may overwrite trace or network ` +
          `data of earlier pass without a unique passName (repeated name: ${passName}.`);
    }
    usedNames.add(passName);
  });
}
 
function getGatherersNeededByAudits(audits) {
  // It's possible we didn't get given any audits (but existing audit results), in which case
  // there is no need to do any work here.
  if (!audits) {
    return new Set();
  }
 
  return audits.reduce((list, audit) => {
    audit.meta.requiredArtifacts.forEach(artifact => list.add(artifact));
    return list;
  }, new Set());
}
 
function assertValidAudit(auditDefinition, auditPath) {
  const auditName = auditPath || auditDefinition.meta.name;
 
  if (typeof auditDefinition.audit !== 'function') {
    throw new Error(`${auditName} has no audit() method.`);
  }
 
  if (typeof auditDefinition.meta.name !== 'string') {
    throw new Error(`${auditName} has no meta.name property, or the property is not a string.`);
  }
 
  if (typeof auditDefinition.meta.category !== 'string') {
    throw new Error(`${auditName} has no meta.category property, or the property is not a string.`);
  }
 
  if (typeof auditDefinition.meta.description !== 'string') {
    throw new Error(
      `${auditName} has no meta.description property, or the property is not a string.`
    );
  }
 
  if (!Array.isArray(auditDefinition.meta.requiredArtifacts)) {
    throw new Error(
      `${auditName} has no meta.requiredArtifacts property, or the property is not an array.`
    );
  }
 
  if (typeof auditDefinition.generateAuditResult !== 'function') {
    throw new Error(
      `${auditName} has no generateAuditResult() method. ` +
        'Did you inherit from the proper base class?'
    );
  }
}
 
function expandArtifacts(artifacts) {
  if (!artifacts) {
    return null;
  }
  // currently only trace logs and performance logs should be imported
  if (artifacts.traces) {
    Object.keys(artifacts.traces).forEach(key => {
      log.log('info', 'Normalizng trace contents into expected state...');
      let trace = require(artifacts.traces[key]);
      // Before Chrome 54.0.2816 (codereview.chromium.org/2161583004), trace was
      // an array of trace events. After this point, trace is an object with a
      // traceEvents property. Normalize to new format.
      if (Array.isArray(trace)) {
        trace = {
          traceEvents: trace
        };
      }
      trace = cleanTrace(trace);
 
      artifacts.traces[key] = trace;
    });
  }
 
  if (artifacts.performanceLog) {
    if (typeof artifacts.performanceLog === 'string') {
      // Support older format of a single performance log.
      const log = require(artifacts.performanceLog);
      artifacts.networkRecords = {
        [Audit.DEFAULT_PASS]: recordsFromLogs(log)
      };
    } else {
      artifacts.networkRecords = {};
      Object.keys(artifacts.performanceLog).forEach(key => {
        const log = require(artifacts.performanceLog[key]);
        artifacts.networkRecords[key] = recordsFromLogs(log);
      });
    }
  }
 
  return artifacts;
}
 
function merge(base, extension) {
  if (typeof base === 'undefined') {
    return extension;
  } else if (Array.isArray(extension)) {
    if (!Array.isArray(base)) throw new TypeError(`Expected array but got ${typeof base}`);
    return base.concat(extension);
  } else if (typeof extension === 'object') {
    if (typeof base !== 'object') throw new TypeError(`Expected object but got ${typeof base}`);
    Object.keys(extension).forEach(key => {
      base[key] = merge(base[key], extension[key]);
    });
    return base;
  }
 
  return extension;
}
 
function deepClone(json) {
  return JSON.parse(JSON.stringify(json));
}
 
class Config {
  /**
   * @constructor
   * @param {!LighthouseConfig} configJSON
   * @param {string=} configPath The absolute path to the config file, if there is one.
   */
  constructor(configJSON, configPath) {
    if (!configJSON) {
      configJSON = defaultConfig;
      configPath = path.resolve(__dirname, defaultConfigPath);
    }
 
    if (configPath && !path.isAbsolute(configPath)) {
      throw new Error('configPath must be an absolute path.');
    }
 
    // We don't want to mutate the original config object
    const inputConfig = configJSON;
    configJSON = deepClone(configJSON);
 
    // Copy arrays that could contain plugins to allow for programmatic
    // injection of plugins.
    if (Array.isArray(inputConfig.passes)) {
      configJSON.passes.forEach((pass, i) => {
        pass.gatherers = Array.from(inputConfig.passes[i].gatherers);
      });
    }
    if (Array.isArray(inputConfig.audits)) {
      configJSON.audits = Array.from(inputConfig.audits);
    }
 
    // Extend the default config if specified
    if (configJSON.extends) {
      configJSON = Config.extendConfigJSON(deepClone(defaultConfig), configJSON);
    }
 
    // Store the directory of the config path, if one was provided.
    this._configDir = configPath ? path.dirname(configPath) : undefined;
 
    this._passes = configJSON.passes || null;
    this._auditResults = configJSON.auditResults || null;
    if (this._auditResults && !Array.isArray(this._auditResults)) {
      throw new Error('config.auditResults must be an array');
    }
 
    this._aggregations = configJSON.aggregations || null;
 
    this._audits = Config.requireAudits(configJSON.audits, this._configDir);
    this._artifacts = expandArtifacts(configJSON.artifacts);
 
    // validatePasses must follow after audits are required
    validatePasses(configJSON.passes, this._audits, this._configDir);
  }
 
  /**
   * @param {!Object} baseJSON The JSON of the configuration to extend
   * @param {!Object} extendJSON The JSON of the extensions
   * @return {!Object}
   */
  static extendConfigJSON(baseJSON, extendJSON) {
    if (extendJSON.passes) {
      extendJSON.passes.forEach(pass => {
        const basePass = baseJSON.passes.find(candidate => candidate.passName === pass.passName);
        if (!basePass || !pass.passName) {
          baseJSON.passes.push(pass);
        } else {
          merge(basePass, pass);
        }
      });
 
      delete extendJSON.passes;
    }
 
    return merge(baseJSON, extendJSON);
  }
 
  /**
   * Take an array of audits and audit paths and require any paths (possibly
   * relative to the optional `configPath`) using `Runner.resolvePlugin`,
   * leaving only an array of Audits.
   * @param {?Array<(string|!Audit)>} audits
   * @param {string=} configPath
   * @return {?Array<!Audit>}
   */
  static requireAudits(audits, configPath) {
    if (!audits) {
      return null;
    }
 
    const coreList = Runner.getAuditList();
    return audits.map(pathOrAuditClass => {
      let AuditClass;
      if (typeof pathOrAuditClass === 'string') {
        const path = pathOrAuditClass;
        // See if the audit is a Lighthouse core audit.
        const coreAudit = coreList.find(a => a === `${path}.js`);
        let requirePath = `../audits/${path}`;
        if (!coreAudit) {
          // Otherwise, attempt to find it elsewhere. This throws if not found.
          requirePath = Runner.resolvePlugin(path, configPath, 'audit');
        }
        AuditClass = require(requirePath);
        assertValidAudit(AuditClass, path);
      } else {
        AuditClass = pathOrAuditClass;
        assertValidAudit(AuditClass);
      }
 
      return AuditClass;
    });
  }
 
  /** @type {string} */
  get configDir() {
    return this._configDir;
  }
 
  /** @type {Array<!Pass>} */
  get passes() {
    return this._passes;
  }
 
  /** @type {Array<!Audit>} */
  get audits() {
    return this._audits;
  }
 
  /** @type {Array<!AuditResult>} */
  get auditResults() {
    return this._auditResults;
  }
 
  /** @type {Array<!Artifacts>} */
  get artifacts() {
    return this._artifacts;
  }
 
  /** @type {Array<!Aggregation>} */
  get aggregations() {
    return this._aggregations;
  }
}
 
module.exports = Config;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/

Statements: 21.05% (28 / 133)      Branches: 0% (0 / 69)      Functions: 0% (0 / 20)      Lines: 21.37% (28 / 131)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/
File Statements Branches Functions Lines
accessibility.js 33.33% (5 / 15) 0% (0 / 11) 0% (0 / 4) 33.33% (5 / 15)
cards.js 33.33% (5 / 15) 0% (0 / 7) 0% (0 / 1) 33.33% (5 / 15)
formatter.js 5.26% (1 / 19) 0% (0 / 8) 0% (0 / 7) 5.26% (1 / 19)
null-formatter.js 28.57% (2 / 7) 0% (0 / 3) 0% (0 / 1) 33.33% (2 / 6)
speedline-formatter.js 38.46% (5 / 13) 0% (0 / 7) 0% (0 / 2) 38.46% (5 / 13)
table.js 10.87% (5 / 46) 0% (0 / 26) 0% (0 / 4) 11.11% (5 / 45)
url-list.js 27.78% (5 / 18) 0% (0 / 7) 0% (0 / 1) 27.78% (5 / 18)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/accessibility.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/accessibility.js

Statements: 33.33% (5 / 15)      Branches: 0% (0 / 11)      Functions: 0% (0 / 4)      Lines: 33.33% (5 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                                      1 1 1 1                                                                               1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const path = require('path');
const fs = require('fs');
const Formatter = require('./formatter');
const html = fs.readFileSync(path.join(__dirname, 'partials/accessibility.html'), 'utf8');
 
class Accessibilty extends Formatter {
  static getFormatter(type) {
    switch (type) {
      case 'pretty':
        return function(info) {
          if (info === null ||
              typeof info === 'undefined' ||
              typeof info.impact === 'undefined' ||
              typeof info.helpUrl === 'undefined' ||
              typeof info.nodes === 'undefined' ||
              !Array.isArray(info.nodes)) {
            return '';
          }
 
          const output = `      - Rating: ${info.impact}\n` +
          `      - See: ${info.helpUrl}\n` +
          `      - Nodes: ${info.nodes.length} nodes identified (see HTML output for details)\n`;
          return output;
        };
 
      case 'html':
        // Returns a handlebars string to be used by the Report.
        return html;
 
      default:
        throw new Error('Unknown formatter type');
    }
  }
 
  static getHelpers() {
    return {
      gt(a, b) {
        return a > b;
      }
    };
  }
}
 
module.exports = Accessibilty;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/cards.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/cards.js

Statements: 33.33% (5 / 15)      Branches: 0% (0 / 7)      Functions: 0% (0 / 1)      Lines: 33.33% (5 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                                      1 1 1 1                                                     1    
/**
 * @license
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Formatter = require('./formatter');
const path = require('path');
const fs = require('fs');
const html = fs.readFileSync(path.join(__dirname, 'partials/cards.html'), 'utf8');
 
class Card extends Formatter {
  static getFormatter(type) {
    switch (type) {
      case 'pretty':
        return result => {
          if (!result || !Array.isArray(result)) {
            return '';
          }
          let output = '';
          result.forEach(item => {
            output += `    - ${item.title}: ${item.value}\n`;
          });
          return output;
        };
 
      case 'html':
        // Returns a handlebars string to be used by the Report.
        return html;
 
      default:
        throw new Error('Unknown formatter type');
    }
  }
}
 
module.exports = Card;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/formatter.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/formatter.js

Statements: 5.26% (1 / 19)      Branches: 0% (0 / 8)      Functions: 0% (0 / 7)      Lines: 5.26% (1 / 19)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88                                                                                                                                                                          1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
class Formatter {
 
  static get CAPITAL_LETTERS() {
    return /([A-Z])/g;
  }
 
  static get SUPPORTED_FORMATS() {
    // Get the available formatters if they don't already exist.
    if (!this._formatters) {
      this._getFormatters();
    }
 
    // From the formatters we can establish a master list of supported format names.
    if (!this._supportedFormatsNames) {
      this._generateSupportedFormats();
    }
 
    return this._supportedFormatsNames;
  }
 
  static _getFormatters() {
    this._formatters = {
      accessibility: require('./accessibility'),
      card: require('./cards'),
      criticalRequestChains: require('./critical-request-chains'),
      urllist: require('./url-list'),
      null: require('./null-formatter'),
      speedline: require('./speedline-formatter'),
      table: require('./table'),
      userTimings: require('./user-timings')
    };
  }
 
  static _generateSupportedFormats() {
    const formatNames = Object.keys(this._formatters);
    this._supportedFormatsNames = formatNames.reduce((prev, format) => {
      // Reformulates names like criticalNetworkChains to CRITICAL_NETWORK_CHAINS so they appear
      // like a bunch of constants.
      const formatName = format.replace(Formatter.CAPITAL_LETTERS, '_$1').toUpperCase();
      prev[formatName] = format;
      return prev;
    }, {});
  }
 
  static getByName(name) {
    if (!this._formatters) {
      this._getFormatters();
    }
 
    if (!this._formatters[name]) {
      throw new Error(`Unknown formatter: ${name}`);
    }
 
    return this._formatters[name];
  }
 
  static getFormatter() {
    throw new Error('Formatter must implement getPrettyFormatter()');
  }
 
  /**
   * Optional function to get any Handlebars helpers this formatter expects to need.
   */
  static getHelpers() {}
}
 
module.exports = Formatter;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/null-formatter.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/null-formatter.js

Statements: 28.57% (2 / 7)      Branches: 0% (0 / 3)      Functions: 0% (0 / 1)      Lines: 33.33% (2 / 6)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39                                      1                                 1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Formatter = require('./formatter');
 
class NullFormatter extends Formatter {
  static getFormatter(type) {
    switch (type) {
      case 'pretty':
        return _ => '';
 
      case 'html':
        return '';
 
      default:
        throw new Error('Unknown formatter type');
    }
  }
}
 
module.exports = NullFormatter;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/speedline-formatter.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/speedline-formatter.js

Statements: 38.46% (5 / 13)      Branches: 0% (0 / 7)      Functions: 0% (0 / 2)      Lines: 38.46% (5 / 13)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51                                    1 1 1 1                                                     1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const Formatter = require('./formatter');
const path = require('path');
const fs = require('fs');
const html = fs.readFileSync(path.join(__dirname, 'partials/speedline.html'), 'utf8');
 
class SpeedlineFormatter extends Formatter {
  static getFormatter(type) {
    switch (type) {
      case 'pretty':
        return function(info) {
          if (!info || !info.timings) {
            return '';
          }
 
          const output = `    - First Visual Change: ${info.timings.firstVisualChange}ms\n` +
          `    - Last Visual Change: ${info.timings.visuallyComplete}ms\n`;
 
          return output;
        };
 
      case 'html':
        // Returns a handlebars string to be used by the Report.
        return html;
 
      default:
        throw new Error('Unknown formatter type');
    }
  }
}
 
module.exports = SpeedlineFormatter;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/table.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/table.js

Statements: 10.87% (5 / 46)      Branches: 0% (0 / 26)      Functions: 0% (0 / 4)      Lines: 11.11% (5 / 45)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134                                      1 1 1 1                                                                                                                                                                                                                         1    
/**
 * @license
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Formatter = require('./formatter');
const path = require('path');
const fs = require('fs');
const html = fs.readFileSync(path.join(__dirname, 'partials/table.html'), 'utf8');
 
class Table extends Formatter {
  static getFormatter(type) {
    switch (type) {
      case 'pretty':
        return result => {
          let output = '';
 
          if (!result || !result.results || !result.tableHeadings) {
            return output;
          }
 
          const table = Table.createTable(result.tableHeadings, result.results);
          const headings = Object.keys(result.tableHeadings).map(key => {
            return result.tableHeadings[key].toUpperCase();
          });
 
          output += `      ${headings.join(' ')}\n`;
 
          table.rows.forEach(row => {
            output += '      ';
            row.cols.forEach(col => {
              // Omit code snippet cols and image previews.
              if (!col || col.startsWith('`') && col.endsWith('`') ||
                  col.startsWith('[![Image preview]')) {
                output += '- ';
              } else {
                output += `${col} `;
              }
            });
            output += '\n';
          });
          return output;
        };
 
      case 'html':
        // Returns a handlebars string to be used by the Report.
        return html;
 
      default:
        throw new Error('Unknown formatter type');
    }
  }
 
  /**
   * Preps a formatted table (headings/col vals) for output.
   * @param {!Object<string>} headings for the table. The order of this
   *     object's key/value pairs determines the order of the HTML table headings.
   *     There is special handling for certain keys:
   *       preview {url: string, mimeType: string}: For image mimetypes, wraps
   *           the value in a markdown image.
   *       code: wraps the value in single ` for a markdown code snippet.
   *       pre: wraps the value in triple ``` for a markdown code block.
   *       lineCol: combines the values for the line and col keys into a single
   *                value "line/col".
   *       isEval: returns "yes" if the script was eval'd.
   *       All other values are passed through as is.
   * @param {!Array<!Object>} results Audit results.
   * @return {{headings: !Array<string>, rows: !Array<{cols: !Array<*>}>}}
   */
  static createTable(headings = {}, results = []) {
    const headingKeys = Object.keys(headings);
 
    const rows = results.map(result => {
      const cols = headingKeys.map(key => {
        let value = result[key];
        if (typeof value === 'undefined') {
          value = '--';
        }
 
        switch (key) {
          case 'preview':
            if (/^image/.test(value.mimeType)) {
              // Markdown can't handle URLs with parentheses which aren't automatically encoded
              const encodedUrl = value.url.replace(/\)/g, '%29');
              return `[![Image preview](${encodedUrl} "Image preview")](${encodedUrl})`;
            }
            return '';
          case 'code':
            return '`' + value.trim() + '`';
          case 'pre':
            return '\`\`\`\n' + result[key].trim() + '\`\`\`';
          case 'lineCol':
            return `${result.line}:${result.col}`;
          case 'isEval':
            return value ? 'yes' : '';
          default:
            return String(value);
        }
      });
 
      return {cols};
    });
 
    headings = headingKeys.map(key => headings[key]);
 
    return {headings, rows, headingKeys};
  }
 
  static getHelpers() {
    return {
      createTable(headings, results, opts) {
        return opts.fn(Table.createTable(headings, results));
      }
    };
  }
}
 
module.exports = Table;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/url-list.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/formatters/url-list.js

Statements: 27.78% (5 / 18)      Branches: 0% (0 / 7)      Functions: 0% (0 / 1)      Lines: 27.78% (5 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57                                      1 1 1 1                                                               1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
const Formatter = require('./formatter');
const path = require('path');
const fs = require('fs');
const html = fs.readFileSync(path.join(__dirname, 'partials/url-list.html'), 'utf8');
 
class UrlList extends Formatter {
  static getFormatter(type) {
    switch (type) {
      case 'pretty':
        return resources => {
          if (!Array.isArray(resources)) {
            return '';
          }
 
          let output = '';
          resources.forEach(resource => {
            output += `      ${resource.url}`;
            if (resource.label) {
              output += ` (${resource.label})`;
            }
            output += '\n';
          });
          return output;
        };
 
      case 'html':
        // Returns a handlebars string to be used by the Report.
        return html;
 
      default:
        throw new Error('Unknown formatter type');
    }
  }
}
 
module.exports = UrlList;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/

Statements: 3.92% (19 / 485)      Branches: 0% (0 / 163)      Functions: 2.74% (2 / 73)      Lines: 4.05% (19 / 469)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/
File Statements Branches Functions Lines
devtools-log.js 10% (1 / 10) 0% (0 / 5) 0% (0 / 6) 10% (1 / 10)
driver.js 4.38% (13 / 297) 0% (0 / 98) 3.92% (2 / 51) 4.48% (13 / 290)
gather-runner.js 2.81% (5 / 178) 0% (0 / 60) 0% (0 / 16) 2.96% (5 / 169)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/devtools-log.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/devtools-log.js

Statements: 10% (1 / 10)      Branches: 0% (0 / 5)      Functions: 0% (0 / 6)      Lines: 10% (1 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                                                                                                                              1    
/**
 * @license
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
/**
 * @fileoverview This class saves all protocol messages whose method match a particular
 *    regex filter. Used when saving assets for later analysis by another tool such as
 *    Webpagetest.
 */
class DevtoolsLog {
  /**
   * @param {RegExp=} regexFilter
   */
  constructor(regexFilter) {
    this._filter = regexFilter;
    this._messages = [];
    this._isRecording = false;
  }
 
  /**
   * @return {!Array<{method: string, params: !Object}>}
   */
  get messages() {
    return this._messages;
  }
 
  reset() {
    this._messages = [];
  }
 
  beginRecording() {
    this._isRecording = true;
  }
 
  endRecording() {
    this._isRecording = false;
  }
 
  /**
   * Records a message if method matches filter and recording has been started.
   * @param {{method: string, params: !Object}} message
   */
  record(message) {
    if (this._isRecording && (!this._filter || this._filter.test(message.method))) {
      this._messages.push(message);
    }
  }
}
 
module.exports = DevtoolsLog;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/driver.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/driver.js

Statements: 4.38% (13 / 297)      Branches: 0% (0 / 98)      Functions: 3.92% (2 / 51)      Lines: 4.48% (13 / 290)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893                                    1 1 1 1 1   1 1   1       1                                           1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 1                                                                                                                               1                       1    
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const NetworkRecorder = require('../lib/network-recorder');
const emulation = require('../lib/emulation');
const Element = require('../lib/element');
const EventEmitter = require('events').EventEmitter;
const URL = require('../lib/url-shim');
 
const log = require('../lib/log.js');
const DevtoolsLog = require('./devtools-log');
 
const PAUSE_AFTER_LOAD = 500;
 
class Driver {
  static get MAX_WAIT_FOR_FULLY_LOADED() {
    return 25 * 1000;
  }
 
  /**
   * @param {!Connection} connection
   */
  constructor(connection) {
    this._traceEvents = [];
    this._traceCategories = Driver.traceCategories;
    this._eventEmitter = new EventEmitter();
    this._connection = connection;
    // currently only used by WPT where just Page and Network are needed
    this._devtoolsLog = new DevtoolsLog(/^(Page|Network)\./);
    connection.on('notification', event => {
      this._devtoolsLog.record(event);
      this._eventEmitter.emit(event.method, event.params);
    });
    this.online = true;
    this._domainEnabledCounts = new Map();
  }
 
  static get traceCategories() {
    return [
      '-*', // exclude default
      'toplevel',
      'blink.console',
      'blink.user_timing',
      'benchmark',
      'loading',
      'latencyInfo',
      'devtools.timeline',
      'disabled-by-default-devtools.timeline',
      'disabled-by-default-devtools.timeline.frame',
      'disabled-by-default-devtools.timeline.stack',
      // Flipped off until bugs.chromium.org/p/v8/issues/detail?id=5820 is fixed in Stable
      // 'disabled-by-default-v8.cpu_profiler',
      // 'disabled-by-default-v8.cpu_profiler.hires',
      'disabled-by-default-devtools.screenshot'
    ];
  }
 
  /**
   * @return {!Array<{method: string, params: !Object}>}
   */
  get devtoolsLog() {
    return this._devtoolsLog.messages;
  }
 
  /**
   * @return {!Promise<null>}
   */
  connect() {
    return this._connection.connect();
  }
 
  disconnect() {
    return this._connection.disconnect();
  }
 
  /**
   * Bind listeners for protocol events
   * @param {!string} eventName
   * @param {function(...)} cb
   */
  on(eventName, cb) {
    if (this._eventEmitter === null) {
      throw new Error('connect() must be called before attempting to listen to events.');
    }
 
    // log event listeners being bound
    log.formatProtocol('listen for event =>', {method: eventName}, 'verbose');
    this._eventEmitter.on(eventName, cb);
  }
 
  /**
   * Bind a one-time listener for protocol events. Listener is removed once it
   * has been called.
   * @param {!string} eventName
   * @param {function(...)} cb
   */
  once(eventName, cb) {
    if (this._eventEmitter === null) {
      throw new Error('connect() must be called before attempting to listen to events.');
    }
    // log event listeners being bound
    log.formatProtocol('listen once for event =>', {method: eventName}, 'verbose');
    this._eventEmitter.once(eventName, cb);
  }
 
  /**
   * Unbind event listeners
   * @param {!string} eventName
   * @param {function(...)} cb
   */
  off(eventName, cb) {
    if (this._eventEmitter === null) {
      throw new Error('connect() must be called before attempting to remove an event listener.');
    }
 
    this._eventEmitter.removeListener(eventName, cb);
  }
 
  /**
   * Debounce enabling or disabling domains to prevent driver users from
   * stomping on each other. Maintains an internal count of the times a domain
   * has been enabled. Returns false if the command would have no effect (domain
   * is already enabled or disabled), or if command would interfere with another
   * user of that domain (e.g. two gatherers have enabled a domain, both need to
   * disable it for it to be disabled). Returns true otherwise.
   * @param {string} domain
   * @param {boolean} enable
   * @return {boolean}
   * @private
   */
  _shouldToggleDomain(domain, enable) {
    const enabledCount = this._domainEnabledCounts.get(domain) || 0;
    const newCount = enabledCount + (enable ? 1 : -1);
    this._domainEnabledCounts.set(domain, Math.max(0, newCount));
 
    // Switching to enabled or disabled, respectively.
    if ((enable && newCount === 1) || (!enable && newCount === 0)) {
      log.verbose('Driver', `${domain}.${enable ? 'enable' : 'disable'}`);
      return true;
    } else {
      if (newCount < 0) {
        log.error('Driver', `Attempted to disable domain '${domain}' when already disabled.`);
      }
      return false;
    }
  }
 
  /**
   * Call protocol methods
   * @param {!string} method
   * @param {!Object} params
   * @return {!Promise}
   */
  sendCommand(method, params) {
    const domainCommand = /^(\w+)\.(enable|disable)$/.exec(method);
    if (domainCommand) {
      const enable = domainCommand[2] === 'enable';
      if (!this._shouldToggleDomain(domainCommand[1], enable)) {
        return Promise.resolve();
      }
    }
 
    return this._connection.sendCommand(method, params);
  }
 
  /**
   * Returns whether a domain is currently enabled.
   * @param {string} domain
   * @return {boolean}
   */
  isDomainEnabled(domain) {
    // Defined, non-zero elements of the domains map are enabled.
    return !!this._domainEnabledCounts.get(domain);
  }
 
  /**
   * Add a script to run at load time of all future page loads.
   * @param {string} scriptSource
   * @return {!Promise<string>} Identifier of the added script.
   */
  evaluateScriptOnLoad(scriptSource) {
    return this.sendCommand('Page.addScriptToEvaluateOnLoad', {
      scriptSource
    });
  }
 
  /**
   * Evaluate an expression in the context of the current page.
   * Returns a promise that resolves on the expression's value.
   * @param {string} expression
   * @return {!Promise<*>}
   */
  evaluateAsync(expression) {
    return new Promise((resolve, reject) => {
      // If this gets to 60s and it hasn't been resolved, reject the Promise.
      const asyncTimeout = setTimeout(
        (_ => reject(new Error('The asynchronous expression exceeded the allotted time of 60s'))),
        60000
      );
 
      this.sendCommand('Runtime.evaluate', {
        // We need to explicitly wrap the raw expression for several purposes:
        // 1. Ensure that the expression will be a native Promise and not a polyfill/non-Promise.
        // 2. Ensure that errors in the expression are captured by the Promise.
        // 3. Ensure that errors captured in the Promise are converted into plain-old JS Objects
        //    so that they can be serialized properly b/c JSON.stringify(new Error('foo')) === '{}'
        expression: `(function wrapInNativePromise() {
          const __nativePromise = window.__nativePromise || Promise;
          return new __nativePromise(function (resolve) {
            return __nativePromise.resolve()
              .then(_ => ${expression})
              .catch(${wrapRuntimeEvalErrorInBrowser.toString()})
              .then(resolve);
          });
        }())`,
        includeCommandLineAPI: true,
        awaitPromise: true,
        returnByValue: true
      }).then(result => {
        clearTimeout(asyncTimeout);
        const value = result.result.value;
 
        if (result.exceptionDetails) {
          // An error occurred before we could even create a Promise, should be *very* rare
          reject(new Error('an unexpected driver error occurred'));
        } if (value && value.__failedInBrowser) {
          reject(Object.assign(new Error(), value));
        } else {
          resolve(value);
        }
      }).catch(err => {
        clearTimeout(asyncTimeout);
        reject(err);
      });
    });
  }
 
  getSecurityState() {
    return new Promise((resolve, reject) => {
      this.once('Security.securityStateChanged', data => {
        this.sendCommand('Security.disable')
          .then(_ => resolve(data), reject);
      });
 
      this.sendCommand('Security.enable').catch(reject);
    });
  }
 
  getServiceWorkerVersions() {
    return new Promise((resolve, reject) => {
      this.once('ServiceWorker.workerVersionUpdated', data => {
        this.sendCommand('ServiceWorker.disable')
          .then(_ => resolve(data), reject);
      });
 
      this.sendCommand('ServiceWorker.enable').catch(reject);
    });
  }
 
  getServiceWorkerRegistrations() {
    return new Promise((resolve, reject) => {
      this.once('ServiceWorker.workerRegistrationUpdated', data => {
        this.sendCommand('ServiceWorker.disable')
          .then(_ => resolve(data), reject);
      });
 
      this.sendCommand('ServiceWorker.enable').catch(reject);
    });
  }
 
  /**
   * Rejects if any open tabs would share a service worker with the target URL.
   * This includes the target tab, so navigation to something like about:blank
   * should be done before calling.
   * @param {!string} pageUrl
   * @return {!Promise}
   */
  assertNoSameOriginServiceWorkerClients(pageUrl) {
    let registrations;
    let versions;
    return this.getServiceWorkerRegistrations().then(data => {
      registrations = data.registrations;
    }).then(_ => this.getServiceWorkerVersions()).then(data => {
      versions = data.versions;
    }).then(_ => {
      const origin = new URL(pageUrl).origin;
 
      registrations
        .filter(reg => {
          const swOrigin = new URL(reg.scopeURL).origin;
 
          return origin === swOrigin;
        })
        .forEach(reg => {
          versions.forEach(ver => {
            // Ignore workers unaffiliated with this registration
            if (ver.registrationId !== reg.registrationId) {
              return;
            }
 
            // Throw if service worker for this origin has active controlledClients.
            if (ver.controlledClients && ver.controlledClients.length > 0) {
              throw new Error('You probably have multiple tabs open to the same origin.');
            }
          });
        });
    });
  }
 
  /**
   * If our main document URL redirects, we will update options.url accordingly
   * As such, options.url will always represent the post-redirected URL.
   * options.initialUrl is the pre-redirect URL that things started with
   * @param {!Object} opts
   */
  enableUrlUpdateIfRedirected(opts) {
    this._networkRecorder.on('requestloaded', redirectRequest => {
      // Quit if this is not a redirected request
      if (!redirectRequest.redirectSource) {
        return;
      }
      const earlierRequest = redirectRequest.redirectSource;
      if (earlierRequest.url === opts.url) {
        opts.url = redirectRequest.url;
      }
    });
  }
 
  /**
   * Returns a promise that resolves when the network has been idle for
   * `pauseAfterLoadMs` ms and a method to cancel internal network listeners and
   * timeout.
   * @param {string} pauseAfterLoadMs
   * @return {{promise: !Promise, cancel: function()}}
   * @private
   */
  _waitForNetworkIdle(pauseAfterLoadMs) {
    let idleTimeout;
    let cancel;
 
    const promise = new Promise((resolve, reject) => {
      const onIdle = () => {
        // eslint-disable-next-line no-use-before-define
        this._networkRecorder.once('networkbusy', onBusy);
        idleTimeout = setTimeout(_ => {
          cancel();
          resolve();
        }, pauseAfterLoadMs);
      };
 
      const onBusy = () => {
        this._networkRecorder.once('networkidle', onIdle);
        clearTimeout(idleTimeout);
      };
 
      cancel = () => {
        clearTimeout(idleTimeout);
        this._networkRecorder.removeListener('networkbusy', onBusy);
        this._networkRecorder.removeListener('networkidle', onIdle);
      };
 
      if (this._networkRecorder.isIdle()) {
        onIdle();
      } else {
        onBusy();
      }
    });
 
    return {
      promise,
      cancel
    };
  }
 
  /**
   * Return a promise that resolves `pauseAfterLoadMs` after the load event
   * fires and a method to cancel internal listeners and timeout.
   * @param {number} pauseAfterLoadMs
   * @return {{promise: !Promise, cancel: function()}}
   * @private
   */
  _waitForLoadEvent(pauseAfterLoadMs) {
    let loadListener;
    let loadTimeout;
 
    const promise = new Promise((resolve, reject) => {
      loadListener = function() {
        loadTimeout = setTimeout(resolve, pauseAfterLoadMs);
      };
      this.once('Page.loadEventFired', loadListener);
    });
    const cancel = () => {
      this.off('Page.loadEventFired', loadListener);
      clearTimeout(loadTimeout);
    };
 
    return {
      promise,
      cancel
    };
  }
 
  /**
   * Returns a promise that resolves when:
   * - it's been pauseAfterLoadMs milliseconds after both onload and the network
   * has gone idle, or
   * - maxWaitForLoadedMs milliseconds have passed.
   * See https://github.com/GoogleChrome/lighthouse/issues/627 for more.
   * @param {number} pauseAfterLoadMs
   * @param {number} maxWaitForLoadedMs
   * @return {!Promise}
   * @private
   */
  _waitForFullyLoaded(pauseAfterLoadMs, maxWaitForLoadedMs) {
    let maxTimeoutHandle;
 
    // Listener for onload. Resolves pauseAfterLoadMs ms after load.
    const waitForLoadEvent = this._waitForLoadEvent(pauseAfterLoadMs);
    // Network listener. Resolves when the network has been idle for pauseAfterLoadMs.
    const waitForNetworkIdle = this._waitForNetworkIdle(pauseAfterLoadMs);
 
    // Wait for both load promises. Resolves on cleanup function the clears load
    // timeout timer.
    const loadPromise = Promise.all([
      waitForLoadEvent.promise,
      waitForNetworkIdle.promise
    ]).then(_ => {
      return function() {
        log.verbose('Driver', 'loadEventFired and network considered idle');
        clearTimeout(maxTimeoutHandle);
      };
    });
 
    // Last resort timeout. Resolves maxWaitForLoadedMs ms from now on
    // cleanup function that removes loadEvent and network idle listeners.
    const maxTimeoutPromise = new Promise((resolve, reject) => {
      maxTimeoutHandle = setTimeout(resolve, maxWaitForLoadedMs);
    }).then(_ => {
      return function() {
        log.warn('Driver', 'Timed out waiting for page load. Moving on...');
        waitForLoadEvent.cancel();
        waitForNetworkIdle.cancel();
      };
    });
 
    // Wait for load or timeout and run the cleanup function the winner returns.
    return Promise.race([
      loadPromise,
      maxTimeoutPromise
    ]).then(cleanup => cleanup());
  }
 
  /**
   * Navigate to the given URL. Use of this method directly isn't advised: if
   * the current page is already at the given URL, navigation will not occur and
   * so the returned promise will only resolve after the MAX_WAIT_FOR_FULLY_LOADED
   * timeout. See https://github.com/GoogleChrome/lighthouse/pull/185 for one
   * possible workaround.
   * @param {string} url
   * @param {!Object} options
   * @return {!Promise}
   */
  gotoURL(url, options = {}) {
    const waitForLoad = options.waitForLoad || false;
    const disableJS = options.disableJavaScript || false;
    const pauseAfterLoadMs = (options.flags && options.flags.pauseAfterLoad) || PAUSE_AFTER_LOAD;
    const maxWaitMs = (options.flags && options.flags.maxWaitForLoad) ||
        Driver.MAX_WAIT_FOR_FULLY_LOADED;
 
    return this.sendCommand('Page.enable')
      .then(_ => this.sendCommand('Emulation.setScriptExecutionDisabled', {value: disableJS}))
      .then(_ => this.sendCommand('Page.navigate', {url}))
      .then(_ => waitForLoad && this._waitForFullyLoaded(pauseAfterLoadMs, maxWaitMs));
  }
 
  /**
  * @param {string} objectId Object ID for the resolved DOM node
  * @param {string} propName Name of the property
  * @return {!Promise<string>} The property value, or null, if property not found
  */
  getObjectProperty(objectId, propName) {
    return new Promise((resolve, reject) => {
      this.sendCommand('Runtime.getProperties', {
        objectId,
        accessorPropertiesOnly: true,
        generatePreview: false,
        ownProperties: false,
      })
      .then(properties => {
        const propertyForName = properties.result
          .find(property => property.name === propName);
 
        if (propertyForName) {
          resolve(propertyForName.value.value);
        } else {
          reject(null);
        }
      });
    });
  }
 
  /**
   * @param {string} name The name of API whose permission you wish to query
   * @return {!Promise<string>} The state of permissions, resolved in a promise.
   *    See https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query.
   */
  queryPermissionState(name) {
    const expressionToEval = `
      navigator.permissions.query({name: '${name}'}).then(result => {
        return result.state;
      })
    `;
 
    return this.evaluateAsync(expressionToEval);
  }
 
  /**
   * @param {string} selector Selector to find in the DOM
   * @return {!Promise<Element>} The found element, or null, resolved in a promise
   */
  querySelector(selector) {
    return this.sendCommand('DOM.getDocument')
      .then(result => result.root.nodeId)
      .then(nodeId => this.sendCommand('DOM.querySelector', {
        nodeId,
        selector
      }))
      .then(element => {
        if (element.nodeId === 0) {
          return null;
        }
        return new Element(element, this);
      });
  }
 
  /**
   * @param {string} selector Selector to find in the DOM
   * @return {!Promise<!Array<!Element>>} The found elements, or [], resolved in a promise
   */
  querySelectorAll(selector) {
    return this.sendCommand('DOM.getDocument')
      .then(result => result.root.nodeId)
      .then(nodeId => this.sendCommand('DOM.querySelectorAll', {
        nodeId,
        selector
      }))
      .then(nodeList => {
        const elementList = [];
        nodeList.nodeIds.forEach(nodeId => {
          if (nodeId !== 0) {
            elementList.push(new Element({nodeId}, this));
          }
        });
        return elementList;
      });
  }
 
  beginTrace() {
    const tracingOpts = {
      categories: this._traceCategories.join(','),
      transferMode: 'ReturnAsStream',
      options: 'sampling-frequency=10000'  // 1000 is default and too slow.
    };
 
    // Check any domains that could interfere with or add overhead to the trace.
    if (this.isDomainEnabled('Debugger')) {
      throw new Error('Debugger domain enabled when starting trace');
    }
    if (this.isDomainEnabled('CSS')) {
      throw new Error('CSS domain enabled when starting trace');
    }
    if (this.isDomainEnabled('DOM')) {
      throw new Error('DOM domain enabled when starting trace');
    }
 
    this._devtoolsLog.reset();
    this._devtoolsLog.beginRecording();
 
    // Enable Page domain to wait for Page.loadEventFired
    return this.sendCommand('Page.enable')
      .then(_ => this.sendCommand('Tracing.start', tracingOpts));
  }
 
  /**
   * @param {number=} pauseBeforeTraceEndMs Wait this many milliseconds before ending the trace
   */
  endTrace(pauseBeforeTraceEndMs = 0) {
    return new Promise((resolve, reject) => {
      // When the tracing has ended this will fire with a stream handle.
      this.once('Tracing.tracingComplete', streamHandle => {
        this._devtoolsLog.endRecording();
        this._readTraceFromStream(streamHandle)
            .then(traceContents => resolve(traceContents), reject);
      });
 
      // Issue the command to stop tracing after an optional delay.
      // Audits like TTI may require slightly longer trace to find a minimum window size.
      setTimeout(() => this.sendCommand('Tracing.end').catch(reject), pauseBeforeTraceEndMs);
    });
  }
 
  _readTraceFromStream(streamHandle) {
    return new Promise((resolve, reject) => {
      let isEOF = false;
      let result = '';
 
      const readArguments = {
        handle: streamHandle.stream
      };
 
      const onChunkRead = response => {
        if (isEOF) {
          return;
        }
 
        result += response.data;
 
        if (response.eof) {
          isEOF = true;
          return resolve(JSON.parse(result));
        }
 
        return this.sendCommand('IO.read', readArguments).then(onChunkRead);
      };
 
      this.sendCommand('IO.read', readArguments).then(onChunkRead).catch(reject);
    });
  }
 
  beginNetworkCollect(opts) {
    return new Promise((resolve, reject) => {
      this._networkRecords = [];
      this._networkRecorder = new NetworkRecorder(this._networkRecords);
      this.enableUrlUpdateIfRedirected(opts);
 
      this.on('Network.requestWillBeSent', this._networkRecorder.onRequestWillBeSent);
      this.on('Network.requestServedFromCache', this._networkRecorder.onRequestServedFromCache);
      this.on('Network.responseReceived', this._networkRecorder.onResponseReceived);
      this.on('Network.dataReceived', this._networkRecorder.onDataReceived);
      this.on('Network.loadingFinished', this._networkRecorder.onLoadingFinished);
      this.on('Network.loadingFailed', this._networkRecorder.onLoadingFailed);
      this.on('Network.resourceChangedPriority', this._networkRecorder.onResourceChangedPriority);
 
      this.sendCommand('Network.enable').then(resolve, reject);
    });
  }
 
  endNetworkCollect() {
    return new Promise((resolve, reject) => {
      this.off('Network.requestWillBeSent', this._networkRecorder.onRequestWillBeSent);
      this.off('Network.requestServedFromCache', this._networkRecorder.onRequestServedFromCache);
      this.off('Network.responseReceived', this._networkRecorder.onResponseReceived);
      this.off('Network.dataReceived', this._networkRecorder.onDataReceived);
      this.off('Network.loadingFinished', this._networkRecorder.onLoadingFinished);
      this.off('Network.loadingFailed', this._networkRecorder.onLoadingFailed);
      this.off('Network.resourceChangedPriority', this._networkRecorder.onResourceChangedPriority);
 
      resolve(this._networkRecords);
 
      this._networkRecorder = null;
      this._networkRecords = [];
    });
  }
 
  enableRuntimeEvents() {
    return this.sendCommand('Runtime.enable');
  }
 
  beginEmulation(flags) {
    return Promise.resolve().then(_ => {
      if (!flags.disableDeviceEmulation) return emulation.enableNexus5X(this);
    }).then(_ => this.setThrottling(flags, {useThrottling: true}));
  }
 
  setThrottling(flags, passConfig) {
    const p = [];
    if (passConfig.useThrottling) {
      if (!flags.disableNetworkThrottling) p.push(emulation.enableNetworkThrottling(this));
      if (!flags.disableCpuThrottling) p.push(emulation.enableCPUThrottling(this));
    } else {
      p.push(emulation.disableNetworkThrottling(this));
      p.push(emulation.disableCPUThrottling(this));
    }
    return Promise.all(p);
  }
 
  /**
   * Emulate internet disconnection.
   * @return {!Promise}
   */
  goOffline() {
    return this.sendCommand('Network.enable')
      .then(_ => emulation.goOffline(this))
      .then(_ => this.online = false);
  }
 
  /**
   * Enable internet connection, using emulated mobile settings if
   * `options.flags.disableNetworkThrottling` is false.
   * @param {!Object} options
   * @return {!Promise}
   */
  goOnline(options) {
    return this.setThrottling(options.flags, options.config)
        .then(_ => this.online = true);
  }
 
  cleanAndDisableBrowserCaches() {
    return Promise.all([
      this.clearBrowserCache(),
      this.disableBrowserCache()
    ]);
  }
 
  clearBrowserCache() {
    return this.sendCommand('Network.clearBrowserCache');
  }
 
  disableBrowserCache() {
    return this.sendCommand('Network.setCacheDisabled', {cacheDisabled: true});
  }
 
  clearDataForOrigin(url) {
    const origin = new URL(url).origin;
 
    // Clear all types of storage except cookies, so the user isn't logged out.
    //   https://chromedevtools.github.io/debugger-protocol-viewer/tot/Storage/#type-StorageType
    const typesToClear = [
      'appcache',
      // 'cookies',
      'file_systems',
      'indexeddb',
      'local_storage',
      'shader_cache',
      'websql',
      'service_workers',
      'cache_storage'
    ].join(',');
 
    return this.sendCommand('Storage.clearDataForOrigin', {
      origin: origin,
      storageTypes: typesToClear
    });
  }
 
  /**
   * Cache native functions/objects inside window
   * so we are sure polyfills do not overwrite the native implementations
   */
  cacheNatives() {
    return this.evaluateScriptOnLoad(`window.__nativePromise = Promise;
        window.__nativeError = Error;`);
  }
 
  /**
   * Keeps track of calls to a JS function and returns a list of {url, line, col}
   * of the usage. Should be called before page load (in beforePass).
   * @param {string} funcName The function name to track ('Date.now', 'console.time').
   * @return {function(): !Promise<!Array<{url: string, line: number, col: number}>>}
   *     Call this method when you want results.
   */
  captureFunctionCallSites(funcName) {
    const globalVarToPopulate = `window['__${funcName}StackTraces']`;
    const collectUsage = () => {
      return this.evaluateAsync(
          `Promise.resolve(Array.from(${globalVarToPopulate}).map(item => JSON.parse(item)))`)
        .then(result => {
          if (!Array.isArray(result)) {
            throw new Error(
                'Driver failure: Expected evaluateAsync results to be an array ' +
                `but got "${JSON.stringify(result)}" instead.`);
          }
          // Filter out usage from extension content scripts.
          return result.filter(item => !item.isExtension);
        });
    };
 
    const funcBody = captureJSCallUsage.toString();
 
    this.evaluateScriptOnLoad(`
        ${globalVarToPopulate} = new Set();
        (${funcName} = ${funcBody}(${funcName}, ${globalVarToPopulate}))`);
 
    return collectUsage;
  }
 
  blockUrlPatterns(urlPatterns) {
    const promiseArr = urlPatterns.map(url => this.sendCommand('Network.addBlockedURL', {url}));
    return Promise.all(promiseArr);
  }
}
 
/**
 * Tracks function call usage. Used by captureJSCalls to inject code into the page.
 * @param {function(...*): *} funcRef The function call to track.
 * @param {!Set} set An empty set to populate with stack traces. Should be
 *     on the global object.
 * @return {function(...*): *} A wrapper around the original function.
 */
function captureJSCallUsage(funcRef, set) {
  /* global window */
  const __nativeError = window.__nativeError || Error;
  const originalFunc = funcRef;
  const originalPrepareStackTrace = __nativeError.prepareStackTrace;
 
  return function(...args) {
    // Note: this function runs in the context of the page that is being audited.
 
    // See v8's Stack Trace API https://github.com/v8/v8/wiki/Stack-Trace-API#customizing-stack-traces
    __nativeError.prepareStackTrace = function(error, structStackTrace) {
      // First frame is the function we injected (the one that just threw).
      // Second, is the actual callsite of the funcRef we're after.
      const callFrame = structStackTrace[1];
      let url = callFrame.getFileName() || callFrame.getEvalOrigin();
      const line = callFrame.getLineNumber();
      const col = callFrame.getColumnNumber();
      const isEval = callFrame.isEval();
      let isExtension = false;
      const stackTrace = structStackTrace.slice(1).map(callsite => callsite.toString());
 
      // If we don't have an URL, (e.g. eval'd code), use the 2nd entry in the
      // stack trace. First is eval context: eval(<context>):<line>:<col>.
      // Second is the callsite where eval was called.
      // See https://crbug.com/646849.
      if (isEval) {
        url = stackTrace[1];
      }
 
      // Chrome extension content scripts can produce an empty .url and
      // "<anonymous>:line:col" for the first entry in the stack trace.
      if (stackTrace[0].startsWith('<anonymous>')) {
        // Note: Although captureFunctionCallSites filters out crx usage,
        // filling url here provides context. We may want to keep those results
        // some day.
        url = stackTrace[0];
        isExtension = true;
      }
 
      // TODO: add back when we want stack traces.
      // Stack traces were removed from the return object in
      // https://github.com/GoogleChrome/lighthouse/issues/957 so callsites
      // would be unique.
      return {url, args, line, col, isEval, isExtension}; // return value is e.stack
    };
    const e = new __nativeError(`__called ${funcRef.name}__`);
    set.add(JSON.stringify(e.stack));
 
    // Restore prepareStackTrace so future errors use v8's formatter and not
    // our custom one.
    __nativeError.prepareStackTrace = originalPrepareStackTrace;
 
    // eslint-disable-next-line no-invalid-this
    return originalFunc.apply(this, args);
  };
}
 
/**
 * The `exceptionDetails` provided by the debugger protocol does not contain the useful
 * information such as name, message, and stack trace of the error when it's wrapped in a
 * promise. Instead, map to a successful object that contains this information.
 * @param {string|Error} err The error to convert
 * istanbul ignore next
 */
function wrapRuntimeEvalErrorInBrowser(err) {
  err = err || new Error();
  const fallbackMessage = typeof err === 'string' ? err : 'unknown error';
 
  return {
    __failedInBrowser: true,
    name: err.name || 'Error',
    message: err.message || fallbackMessage,
    stack: err.stack || (new Error()).stack,
  };
}
 
module.exports = Driver;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/gather-runner.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/gather-runner.js

Statements: 2.81% (5 / 178)      Branches: 0% (0 / 60)      Functions: 0% (0 / 16)      Lines: 2.96% (5 / 169)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451                                    1 1 1 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const log = require('../lib/log.js');
const Audit = require('../audits/audit');
const path = require('path');
const URL = require('../lib/url-shim');
 
/**
 * Class that drives browser to load the page and runs gatherer lifecycle hooks.
 * Execution sequence when GatherRunner.run() is called:
 *
 * 1. Setup
 *   A. navigate to about:blank
 *   B. driver.connect()
 *   C. GatherRunner.setupDriver()
 *     i. assertNoSameOriginServiceWorkerClients
 *     ii. beginEmulation
 *     iii. enableRuntimeEvents
 *     iv. evaluateScriptOnLoad rescue native Promise from potential polyfill
 *     v. cleanAndDisableBrowserCaches
 *     vi. clearDataForOrigin
 *     vii. blockUrlPatterns
 *
 * 2. For each pass in the config:
 *   A. GatherRunner.beforePass()
 *     i. navigate to about:blank
 *     ii. all gatherer's beforePass()
 *   B. GatherRunner.pass()
 *     i. GatherRunner.loadPage()
 *       b. beginTrace (if requested) & beginNetworkCollect
 *       c. navigate to options.url (and wait for onload)
 *     ii. all gatherer's pass()
 *   C. GatherRunner.afterPass()
 *     i. endTrace (if requested) & endNetworkCollect
 *     ii. all gatherer's afterPass()
 *
 * 3. Teardown
 *   A. GatherRunner.disposeDriver()
 *   B. collect all artifacts and return them
 *     i. collectArtifacts() from completed passes on each gatherer
 *     ii. add trace data and computed artifact methods
 */
class GatherRunner {
  /**
   * Loads about:blank and waits there briefly. Since a Page.reload command does
   * not let a service worker take over, we navigate away and then come back to
   * reload. We do not `waitForLoad` on about:blank since a page load event is
   * never fired on it.
   * @param {!Driver} driver
   * @param {url=} url
   * @param {number=} duration
   * @return {!Promise}
   */
  static loadBlank(driver, url = 'about:blank', duration = 300) {
    return driver.gotoURL(url).then(_ => new Promise(resolve => setTimeout(resolve, duration)));
  }
 
  /**
   * Loads options.url with specified options.
   * @param {!Driver} driver
   * @param {!Object} options
   * @return {!Promise}
   */
  static loadPage(driver, options) {
    return Promise.resolve()
      // Begin tracing only if requested by config.
      .then(_ => options.config.recordTrace && driver.beginTrace())
      // Network is always recorded for internal use, even if not saved as artifact.
      .then(_ => driver.beginNetworkCollect(options))
      // Navigate.
      .then(_ => driver.gotoURL(options.url, {
        waitForLoad: true,
        disableJavaScript: !!options.disableJavaScript,
        flags: options.flags,
      }));
  }
 
  static setupDriver(driver, options) {
    log.log('status', 'Initializing…');
    const resetStorage = !options.flags.disableStorageReset;
    // Enable emulation based on flags
    return driver.assertNoSameOriginServiceWorkerClients(options.url)
      .then(_ => driver.beginEmulation(options.flags))
      .then(_ => driver.enableRuntimeEvents())
      .then(_ => driver.cacheNatives())
      .then(_ => resetStorage && driver.cleanAndDisableBrowserCaches())
      .then(_ => resetStorage && driver.clearDataForOrigin(options.url))
      .then(_ => driver.blockUrlPatterns(options.flags.blockedUrlPatterns || []));
  }
 
  static disposeDriver(driver) {
    // We dont need to hold up the reporting for the reload/disconnect,
    // so we will not return a promise in here.
    log.log('status', 'Disconnecting from browser...');
    driver.disconnect().catch(err => {
      // Ignore disconnecting error if browser was already closed.
      // See https://github.com/GoogleChrome/lighthouse/issues/1583
      if (!(/close\/.*status: 500$/.test(err.message))) {
        log.error('GatherRunner disconnect', err.message);
      }
    });
  }
 
  /**
   * Test any error output from the promise, absorbing non-fatal errors and
   * throwing on fatal ones so that run is stopped.
   * @param {!Promise<*>} promise
   * @return {!Promise<*>}
   */
  static recoverOrThrow(promise) {
    return promise.catch(err => {
      if (err.fatal) {
        throw err;
      }
    });
  }
 
  /**
   * Throws an error if the original network request failed or wasn't found.
   * @param {string} url The URL of the original requested page.
   * @param {{online: boolean}} driver
   * @param {!Array<WebInspector.NetworkRequest>} networkRecords
   */
  static assertPageLoaded(url, driver, networkRecords) {
    const mainRecord = networkRecords.find(record => {
      // record.url is actual request url, so needs to be compared without any URL fragment.
      return URL.equalWithExcludedFragments(record.url, url);
    });
    if (driver.online && (!mainRecord || mainRecord.failed)) {
      const message = mainRecord ? mainRecord.localizedFailDescription : 'timeout reached';
      log.error('GatherRunner', message);
      const error = new Error(`Unable to load the page: ${message}`);
      error.code = 'PAGE_LOAD_ERROR';
      throw error;
    }
  }
 
  /**
   * Navigates to about:blank and calls beforePass() on gatherers before tracing
   * has started and before navigation to the target page.
   * @param {!Object} options
   * @param {!Object<!Array<!Promise<*>>} gathererResults
   * @return {!Promise}
   */
  static beforePass(options, gathererResults) {
    const blankPage = options.config.blankPage;
    const blankDuration = options.config.blankDuration;
    const pass = GatherRunner.loadBlank(options.driver, blankPage, blankDuration);
 
    return options.config.gatherers.reduce((chain, gatherer) => {
      return chain.then(_ => {
        const artifactPromise = Promise.resolve().then(_ => gatherer.beforePass(options));
        gathererResults[gatherer.name] = [artifactPromise];
        return GatherRunner.recoverOrThrow(artifactPromise);
      });
    }, pass);
  }
 
  /**
   * Navigates to requested URL and then runs pass() on gatherers while trace
   * (if requested) is still being recorded.
   * @param {!Object} options
   * @param {!Object<!Array<!Promise<*>>} gathererResults
   * @return {!Promise}
   */
  static pass(options, gathererResults) {
    const driver = options.driver;
    const config = options.config;
    const gatherers = config.gatherers;
 
    const gatherernames = gatherers.map(g => g.name).join(', ');
    const status = 'Loading page & waiting for onload';
    log.log('status', status, gatherernames);
 
    const pass = GatherRunner.loadPage(driver, options).then(_ => {
      log.log('statusEnd', status);
    });
 
    return gatherers.reduce((chain, gatherer) => {
      return chain.then(_ => {
        const artifactPromise = Promise.resolve().then(_ => gatherer.pass(options));
        gathererResults[gatherer.name].push(artifactPromise);
        return GatherRunner.recoverOrThrow(artifactPromise);
      });
    }, pass);
  }
 
  /**
   * Ends tracing and collects trace data (if requested for this pass), and runs
   * afterPass() on gatherers with trace data passed in. Promise resolves with
   * object containing trace and network data.
   * @param {!Object} options
   * @param {!Object<!Array<!Promise<*>>} gathererResults
   * @return {!Promise}
   */
  static afterPass(options, gathererResults) {
    const driver = options.driver;
    const config = options.config;
    const gatherers = config.gatherers;
    const passData = {};
 
    let pass = Promise.resolve();
 
    if (config.recordTrace) {
      pass = pass.then(_ => {
        log.log('status', 'Retrieving trace');
        return driver.endTrace(config.pauseBeforeTraceEndMs);
      }).then(traceContents => {
        // Before Chrome 54.0.2816 (codereview.chromium.org/2161583004),
        // traceContents was an array of trace events; after, traceContents is
        // an object with a traceEvents property. Normalize to object form.
        passData.trace = Array.isArray(traceContents) ?
            {traceEvents: traceContents} : traceContents;
        passData.devtoolsLog = driver.devtoolsLog;
        log.verbose('statusEnd', 'Retrieving trace');
      });
    }
 
    const status = 'Retrieving network records';
    pass = pass.then(_ => {
      log.log('status', status);
      return driver.endNetworkCollect();
    }).then(networkRecords => {
      GatherRunner.assertPageLoaded(options.url, driver, networkRecords);
 
      // Network records only given to gatherers if requested by config.
      config.recordNetwork && (passData.networkRecords = networkRecords);
      log.verbose('statusEnd', status);
    });
 
    pass = gatherers.reduce((chain, gatherer) => {
      const status = `Retrieving: ${gatherer.name}`;
      return chain.then(_ => {
        log.log('status', status);
        const artifactPromise = Promise.resolve().then(_ => gatherer.afterPass(options, passData));
        gathererResults[gatherer.name].push(artifactPromise);
        return GatherRunner.recoverOrThrow(artifactPromise);
      }).then(_ => {
        log.verbose('statusEnd', status);
      });
    }, pass);
 
    // Resolve on tracing data using passName from config.
    return pass.then(_ => passData);
  }
 
  /**
   * Takes the results of each gatherer phase for each gatherer and uses the
   * last produced value (that's not undefined) as the artifact for that
   * gatherer. If a non-fatal error was rejected from a gatherer phase,
   * uses that error object as the artifact instead.
   * @param {!Object<!Array<!Promise<*>>} gathererResults
   * @return {!Promise<!Artifacts>}
   */
  static collectArtifacts(gathererResults) {
    const artifacts = {};
 
    return Object.keys(gathererResults).reduce((chain, gathererName) => {
      return chain.then(_ => {
        const phaseResultsPromises = gathererResults[gathererName];
        return Promise.all(phaseResultsPromises).then(phaseResults => {
          // Take last defined pass result as artifact.
          const definedResults = phaseResults.filter(element => element !== undefined);
          const artifact = definedResults[definedResults.length - 1];
          if (artifact === undefined) {
            throw new Error(`${gathererName} failed to provide an artifact.`);
          }
          artifacts[gathererName] = artifact;
        }, err => {
          // To reach this point, all errors are non-fatal, so return err to
          // runner to handle turning it into an error audit.
          artifacts[gathererName] = err;
        });
      });
    }, Promise.resolve()).then(_ => {
      return artifacts;
    });
  }
 
  static run(passes, options) {
    const driver = options.driver;
    const tracingData = {
      traces: {},
      devtoolsLogs: {},
      networkRecords: {}
    };
 
    if (typeof options.url !== 'string' || options.url.length === 0) {
      return Promise.reject(new Error('You must provide a url to the gather-runner'));
    }
 
    if (typeof options.flags === 'undefined') {
      options.flags = {};
    }
 
    if (typeof options.config === 'undefined') {
      return Promise.reject(new Error('You must provide a config'));
    }
 
    // CPU throttling is temporarily off by default
    if (typeof options.flags.disableCpuThrottling === 'undefined') {
      options.flags.disableCpuThrottling = true;
    }
 
    passes = this.instantiateGatherers(passes, options.config.configDir);
 
    const gathererResults = {};
 
    return driver.connect()
      .then(_ => GatherRunner.loadBlank(driver))
      .then(_ => GatherRunner.setupDriver(driver, options))
 
      // Run each pass
      .then(_ => {
        // If the main document redirects, we'll update this to keep track
        let urlAfterRedirects;
        return passes.reduce((chain, config, passIndex) => {
          const runOptions = Object.assign({}, options, {config});
          return chain
            .then(_ => driver.setThrottling(options.flags, config))
            .then(_ => GatherRunner.beforePass(runOptions, gathererResults))
            .then(_ => GatherRunner.pass(runOptions, gathererResults))
            .then(_ => GatherRunner.afterPass(runOptions, gathererResults))
            .then(passData => {
              // If requested by config, merge trace and network data for this
              // pass into tracingData.
              const passName = config.passName || Audit.DEFAULT_PASS;
              if (config.recordTrace) {
                tracingData.traces[passName] = passData.trace;
                tracingData.devtoolsLogs[passName] = passData.devtoolsLog;
              }
              config.recordNetwork &&
                  (tracingData.networkRecords[passName] = passData.networkRecords);
 
              if (passIndex === 0) {
                urlAfterRedirects = runOptions.url;
              }
            });
        }, Promise.resolve()).then(_ => {
          options.url = urlAfterRedirects;
        });
      })
      .then(_ => GatherRunner.disposeDriver(driver))
      .then(_ => GatherRunner.collectArtifacts(gathererResults))
      .then(artifacts => {
        // Add tracing data and computed artifacts to artifacts object.
        const computedArtifacts = this.instantiateComputedArtifacts();
        Object.assign(artifacts, computedArtifacts, tracingData);
        return artifacts;
      })
      // cleanup on error
      .catch(err => {
        GatherRunner.disposeDriver(driver);
 
        throw err;
      });
  }
 
  static getGathererClass(nameOrGathererClass, configPath) {
    const Runner = require('../runner');
    const coreList = Runner.getGathererList();
 
    let GathererClass;
    if (typeof nameOrGathererClass === 'string') {
      const name = nameOrGathererClass;
 
      // See if the gatherer is a Lighthouse core gatherer.
      const coreGatherer = coreList.find(a => a === `${name}.js`);
      let requirePath = `./gatherers/${name}`;
      if (!coreGatherer) {
        // Otherwise, attempt to find it elsewhere. This throws if not found.
        requirePath = Runner.resolvePlugin(name, configPath, 'gatherer');
      }
 
      GathererClass = require(requirePath);
 
      this.assertValidGatherer(GathererClass, name);
    } else {
      GathererClass = nameOrGathererClass;
      this.assertValidGatherer(GathererClass);
    }
 
    return GathererClass;
  }
 
  static assertValidGatherer(GathererDefinition, gathererName) {
    const gathererInstance = new GathererDefinition();
    gathererName = gathererName || gathererInstance.name || 'gatherer';
 
    if (typeof gathererInstance.beforePass !== 'function') {
      throw new Error(`${gathererName} has no beforePass() method.`);
    }
 
    if (typeof gathererInstance.pass !== 'function') {
      throw new Error(`${gathererName} has no pass() method.`);
    }
 
    if (typeof gathererInstance.afterPass !== 'function') {
      throw new Error(`${gathererName} has no afterPass() method.`);
    }
  }
 
  static instantiateComputedArtifacts() {
    const computedArtifacts = {};
    require('fs').readdirSync(path.join(__dirname, 'computed')).forEach(function(file) {
      // Drop `.js` suffix to keep browserify import happy.
      file = file.replace(/\.js$/, '');
      const ArtifactClass = require('./computed/' + file);
      const artifact = new ArtifactClass();
      // define the request* function that will be exposed on `artifacts`
      computedArtifacts['request' + artifact.name] = artifact.request.bind(artifact);
    });
    return computedArtifacts;
  }
 
  static instantiateGatherers(passes, rootPath) {
    return passes.map(pass => {
      pass.gatherers = pass.gatherers.map(gatherer => {
        // If this is already instantiated, don't do anything else.
        if (typeof gatherer !== 'string') {
          return gatherer;
        }
 
        const GathererClass = GatherRunner.getGathererClass(gatherer, rootPath);
        return new GathererClass();
      });
 
      return pass;
    });
  }
}
 
module.exports = GatherRunner;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/connections/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/connections/

Statements: 11.58% (11 / 95)      Branches: 0% (0 / 22)      Functions: 0% (0 / 15)      Lines: 11.7% (11 / 94)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/connections/
File Statements Branches Functions Lines
connection.js 9.09% (3 / 33) 0% (0 / 6) 0% (0 / 9) 9.09% (3 / 33)
cri.js 12.9% (8 / 62) 0% (0 / 16) 0% (0 / 6) 13.11% (8 / 61)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/connections/connection.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/connections/connection.js

Statements: 9.09% (3 / 33)      Branches: 0% (0 / 6)      Functions: 0% (0 / 9)      Lines: 9.09% (3 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136                                    1 1                                                                                                                                                                                                                                   1    
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const EventEmitter = require('events').EventEmitter;
const log = require('../../lib/log.js');
 
class Connection {
 
  constructor() {
    this._lastCommandId = 0;
    /** @type {!Map<number, {resolve: function(*), reject: function(*), method: string}>}*/
    this._callbacks = new Map();
    this._eventEmitter = new EventEmitter();
  }
 
  /**
   * @return {!Promise}
   */
  connect() {
    return Promise.reject(new Error('Not implemented'));
  }
 
  /**
   * @return {!Promise}
   */
  disconnect() {
    return Promise.reject(new Error('Not implemented'));
  }
 
  /**
   * Call protocol methods
   * @param {!string} method
   * @param {!Object} params
   * @return {!Promise}
   */
  sendCommand(method, params = {}) {
    log.formatProtocol('method => browser', {method, params}, 'verbose');
    const id = ++this._lastCommandId;
    const message = JSON.stringify({id, method, params});
    this.sendRawMessage(message);
    return new Promise((resolve, reject) => {
      this._callbacks.set(id, {resolve, reject, method});
    });
  }
 
  /**
   * Bind listeners for connection events
   * @param {!string} eventName
   * @param {function(...)} cb
   */
  on(eventName, cb) {
    if (eventName !== 'notification') {
      throw new Error('Only supports "notification" events');
    }
    this._eventEmitter.on(eventName, cb);
  }
 
  /* eslint-disable no-unused-vars */
 
  /**
   * @param {string} message
   * @return {!Promise}
   * @protected
   */
  sendRawMessage(message) {
    return Promise.reject(new Error('Not implemented'));
  }
 
  /* eslint-enable no-unused-vars */
 
  /**
   * @param {string} message
   * @return {!Promise}
   * @protected
   */
  handleRawMessage(message) {
    const object = JSON.parse(message);
    // Remote debugging protocol is JSON RPC 2.0 compiant. In terms of that transport,
    // responses to the commands carry "id" property, while notifications do not.
    if (object.id) {
      const callback = this._callbacks.get(object.id);
      this._callbacks.delete(object.id);
 
      return callback.resolve(Promise.resolve().then(_ => {
        if (object.error) {
          log.formatProtocol('method <= browser ERR', {method: callback.method}, 'error');
          throw new Error(`Protocol error (${callback.method}): ${object.error.message}`);
        }
 
        log.formatProtocol('method <= browser OK',
          {method: callback.method, params: object.result}, 'verbose');
        return object.result;
      }));
    }
 
    log.formatProtocol('<= event',
        {method: object.method, params: object.params}, 'verbose');
    this.emitNotification(object.method, object.params);
  }
 
  /**
   * @param {!string} method
   * @param {!Object} params
   * @protected
   */
  emitNotification(method, params) {
    this._eventEmitter.emit('notification', {method, params});
  }
 
  /**
   * @protected
   */
  dispose() {
    this._eventEmitter.removeAllListeners();
    this._eventEmitter = null;
  }
}
 
module.exports = Connection;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/connections/cri.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/connections/cri.js

Statements: 12.9% (8 / 62)      Branches: 0% (0 / 16)      Functions: 0% (0 / 6)      Lines: 13.11% (8 / 61)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161                                    1 1 1 1   1 1 1                                                                                                                                                                                                                                                                         1    
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const Connection = require('./connection.js');
const WebSocket = require('ws');
const http = require('http');
const log = require('../../lib/log.js');
 
const hostname = 'localhost';
const CONNECT_TIMEOUT = 10000;
const DEFAULT_PORT = 9222;
 
class CriConnection extends Connection {
  /**
   * @param {number=} port Optional port number. Defaults to 9222;
   * @constructor
   */
  constructor(port) {
    super();
 
    this.port = port || DEFAULT_PORT;
  }
 
  /**
   * @override
   * @return {!Promise}
   */
  connect() {
    return this._runJsonCommand('new')
      .then(response => this._connectToSocket(response))
      .catch(_ => {
        // headless doesn't support `/json/new` (#970), so we fallback to reuse
        log.warn('CriConnection', 'Cannot create new tab; reusing open tab.');
        return this._runJsonCommand('list').then(tabs => {
          const firstTab = tabs[0];
          if (!Array.isArray(tabs) || !firstTab) {
            return Promise.reject(new Error('Cannot create new tab, and no tabs already open.'));
          }
          // first, we activate it to a foreground tab, then we connect
          return this._runJsonCommand(`activate/${firstTab.id}`)
              .then(_ => this._connectToSocket(firstTab));
        });
      });
  }
 
  /**
   * @param {!Object} response
   * @return {!Promise}
   */
  _connectToSocket(response) {
    const url = response.webSocketDebuggerUrl;
    this._pageId = response.id;
 
    return new Promise((resolve, reject) => {
      const ws = new WebSocket(url, {
        perMessageDeflate: false
      });
      ws.on('open', () => {
        this._ws = ws;
        resolve();
      });
      ws.on('message', data => this.handleRawMessage(data));
      ws.on('close', this.dispose.bind(this));
      ws.on('error', reject);
    });
  }
 
  /**
   * @param {!string} command
   * @return {!Promise<string>}
   */
  _runJsonCommand(command) {
    return new Promise((resolve, reject) => {
      const request = http.get({
        hostname: hostname,
        port: this.port,
        path: '/json/' + command
      }, response => {
        let data = '';
        response.on('data', chunk => {
          data += chunk;
        });
        response.on('end', _ => {
          if (response.statusCode === 200) {
            try {
              resolve(JSON.parse(data));
              return;
            } catch (e) {
              // In the case of 'close' & 'activate' Chromium returns a string rather than JSON: goo.gl/7v27xD
              if (data === 'Target is closing' || data === 'Target activated') {
                return resolve({message: data});
              }
              return reject(e);
            }
          }
          reject(new Error(`Protocol JSON API error (${command}), status: ${response.statusCode}`));
        });
      });
 
      request.setTimeout(CONNECT_TIMEOUT, _ => {
        request.abort();
 
        // After aborting, we expect an ECONNRESET error. Ignore.
        request.on('error', err => {
          if (err.code !== 'ECONNRESET') {
            throw err;
          }
        });
 
        // Reject on error with code specifically indicating timeout in connection setup.
        const err = new Error('Timeout waiting for initial Debugger Protocol connection.');
        err.code = 'CRI_TIMEOUT';
        log.error('CriConnection', err.message);
        reject(err);
      });
    });
  }
 
  /**
   * @override
   */
  disconnect() {
    if (!this._ws) {
      log.warn('CriConnection', 'disconnect() was called without an established connection.');
      return Promise.resolve();
    }
    return this._runJsonCommand(`close/${this._pageId}`).then(_ => {
      this._ws.removeAllListeners();
      this._ws.close();
      this._ws = null;
      this._pageId = null;
    });
  }
 
  /**
   * @override
   * @param {string} message
   */
  sendRawMessage(message) {
    this._ws.send(message);
  }
}
 
module.exports = CriConnection;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/gatherers/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/gatherers/

Statements: 50% (1 / 2)      Branches: 100% (0 / 0)      Functions: 0% (0 / 4)      Lines: 50% (1 / 2)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/gatherers/
File Statements Branches Functions Lines
gatherer.js 50% (1 / 2) 100% (0 / 0) 0% (0 / 4) 50% (1 / 2)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/gatherers/gatherer.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/gather/gatherers/gatherer.js

Statements: 50% (1 / 2)      Branches: 100% (0 / 0)      Functions: 0% (0 / 4)      Lines: 50% (1 / 2)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                                                                                                                                    1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
/**
 * Base class for all gatherers; defines pass lifecycle methods. The artifact
 * from the gatherer is the last not-undefined value returned by a lifecycle
 * method. All methods can return the artifact value directly or return a
 * Promise that resolves to that value.
 *
 * If an Error is thrown (or a Promise that rejects on an Error), the
 * GatherRunner will check for a `fatal` property on the Error. If not set to
 * `true`, the runner will treat it as an error internal to the gatherer and
 * continue execution of any remaining gatherers.
 */
class Gatherer {
  /**
   * @return {string}
   */
  get name() {
    return this.constructor.name;
  }
 
  /* eslint-disable no-unused-vars */
 
  /**
   * Called before navigation to target url.
   * @param {!Object} options
   */
  beforePass(options) { }
 
  /**
   * Called after target page is loaded. If a trace is enabled for this pass,
   * the trace is still being recorded.
   * @param {!Object} options
   */
  pass(options) { }
 
  /**
   * Called after target page is loaded, all gatherer `pass` methods have been
   * executed, and — if generated in this pass — the trace is ended. The trace
   * and record of network activity are provided in `loadData`.
   * @param {!Object} options
   * @param {networkRecords: !Array, trace: {traceEvents: !Array}} loadData
   * @return {*|!Promise<*>}
   */
  afterPass(options, loadData) { }
 
  /* eslint-enable no-unused-vars */
 
}
 
module.exports = Gatherer;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/

Statements: 30.51% (187 / 613)      Branches: 11.21% (26 / 232)      Functions: 10.16% (13 / 128)      Lines: 30.86% (187 / 606)      Ignored: 10 statements, 2 functions, 2 branches     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/
File Statements Branches Functions Lines
asset-saver.js 31.58% (12 / 38) 0% (0 / 2) 25% (1 / 4) 32.43% (12 / 37)
console-quieter.js 27.78% (5 / 18) 0% (0 / 2) 0% (0 / 5) 27.78% (5 / 18)
element.js 8.33% (1 / 12) 0% (0 / 6) 0% (0 / 3) 8.33% (1 / 12)
empty-stub.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
emulation.js 68.75% (22 / 32) 100% (2 / 2) 12.5% (1 / 8) 70.97% (22 / 31)
event-helpers.js 14.29% (3 / 21) 0% (0 / 4) 0% (0 / 2) 14.29% (3 / 21)
file-namer.js 38.46% (5 / 13) 33.33% (3 / 9) 0% (0 / 1) 38.46% (5 / 13)
icons.js 15% (3 / 20) 0% (0 / 10) 0% (0 / 2) 15.79% (3 / 19)
log.js 50% (30 / 60) 28.85% (15 / 52) 37.04% (10 / 27) 50% (30 / 60)
manifest-parser.js 16.06% (22 / 137) 0% (0 / 59) 0% (0 / 16) 16.18% (22 / 136)
network-recorder.js 7.27% (4 / 55) 0% (0 / 12) 0% (0 / 14) 7.27% (4 / 55)
styles-helpers.js 8% (4 / 50) 0% (0 / 32) 0% (0 / 3) 8.33% (4 / 48)
url-shim.js 18% (9 / 50) 11.11% (3 / 27) 0% (0 / 5) 18.37% (9 / 49)
web-inspector.js 62.26% (66 / 106) 20% (3 / 15) 2.63% (1 / 38) 62.26% (66 / 106)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/asset-saver.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/asset-saver.js

Statements: 31.58% (12 / 38)      Branches: 0% (0 / 2)      Functions: 25% (1 / 4)      Lines: 32.43% (12 / 37)      Ignored: 3 statements, 1 function     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146                                    1 1 1 1             1                                                                                           1 1   1 1                 1                                                                   1                                   1            
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const fs = require('fs');
const log = require('../../lighthouse-core/lib/log.js');
const stringifySafe = require('json-stringify-safe');
const Metrics = require('./traces/pwmetrics-events');
 
/**
 * Generate basic HTML page of screenshot filmstrip
 * @param {!Array<{timestamp: number, datauri: string}>} screenshots
 * @return {!string}
 */
function screenshotDump(screenshots) {
  return `
  <!doctype html>
  <meta charset="utf-8">
  <title>screenshots</title>
  <style>
html {
    overflow-x: scroll;
    overflow-y: hidden;
    height: 100%;
    background-image: linear-gradient(to left, #4ca1af , #c4e0e5);
    background-attachment: fixed;
    padding: 10px;
}
body {
    white-space: nowrap;
    background-image: linear-gradient(to left, #4ca1af , #c4e0e5);
    width: 100%;
    margin: 0;
}
img {
    margin: 4px;
}
</style>
  <body>
    <script>
      var shots = ${JSON.stringify(screenshots)};
 
  shots.forEach(s => {
    var i = document.createElement('img');
    i.src = s.datauri;
    i.title = s.timestamp;
    document.body.appendChild(i);
  });
  </script>
  `;
}
 
/**
 * Save entire artifacts object to a single stringified file located at
 * pathWithBasename + .artifacts.log
 * @param {!Artifacts} artifacts
 * @param {string} pathWithBasename
 */
// Set to ignore because testing it would imply testing fs, which isn't strictly necessary.
/* istanbul ignore next */
function saveArtifacts(artifacts, pathWithBasename) {
  const fullPath = `${pathWithBasename}.artifacts.log`;
  // The networkRecords artifacts have circular references
  fs.writeFileSync(fullPath, stringifySafe(artifacts));
  log.log('artifacts file saved to disk', fullPath);
}
 
/**
 * Filter traces and extract screenshots to prepare for saving.
 * @param {!Artifacts} artifacts
 * @param {!Audits} audits
 * @return {!Promise<!Array<{traceData: !Object, html: string}>>}
 */
function prepareAssets(artifacts, audits) {
  const passNames = Object.keys(artifacts.traces);
  const assets = [];
 
  return passNames.reduce((chain, passName) => {
    const trace = artifacts.traces[passName];
    const devtoolsLog = artifacts.devtoolsLogs[passName];
 
    return chain.then(_ => artifacts.requestScreenshots(trace))
      .then(screenshots => {
        const traceData = Object.assign({}, trace);
        const html = screenshotDump(screenshots);
 
        if (audits) {
          const evts = new Metrics(traceData.traceEvents, audits).generateFakeEvents();
          traceData.traceEvents.push(...evts);
        }
        assets.push({
          traceData,
          devtoolsLog,
          html
        });
      });
  }, Promise.resolve())
    .then(_ => assets);
}
 
/**
 * Writes trace(s) and associated screenshot(s) to disk.
 * @param {!Artifacts} artifacts
 * @param {!Audits} audits
 * @param {string} pathWithBasename
 * @return {!Promise}
 */
function saveAssets(artifacts, audits, pathWithBasename) {
  return prepareAssets(artifacts, audits).then(assets => {
    assets.forEach((data, index) => {
      const traceFilename = `${pathWithBasename}-${index}.trace.json`;
      fs.writeFileSync(traceFilename, JSON.stringify(data.traceData, null, 2));
      log.log('trace file saved to disk', traceFilename);
 
      const devtoolsLogFilename = `${pathWithBasename}-${index}.devtoolslog.json`;
      fs.writeFileSync(devtoolsLogFilename, JSON.stringify(data.devtoolsLog, null, 2));
      log.log('devtools log saved to disk', devtoolsLogFilename);
 
      const screenshotsFilename = `${pathWithBasename}-${index}.screenshots.html`;
      fs.writeFileSync(screenshotsFilename, data.html);
      log.log('screenshots saved to disk', screenshotsFilename);
    });
  });
}
 
module.exports = {
  saveArtifacts,
  saveAssets,
  prepareAssets
};
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/console-quieter.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/console-quieter.js

Statements: 27.78% (5 / 18)      Branches: 0% (0 / 2)      Functions: 0% (0 / 5)      Lines: 27.78% (5 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                                          1                                                           1 1 1   1    
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
/* eslint-disable no-console */
 
const log = require('./log.js');
 
class ConsoleQuieter {
 
  static mute(opts) {
    ConsoleQuieter._logs = ConsoleQuieter._logs || [];
 
    console.log = function(...args) {
      ConsoleQuieter._logs.push({type: 'log', args, prefix: opts.prefix});
    };
    console.warn = function(...args) {
      ConsoleQuieter._logs.push({type: 'warn', args, prefix: opts.prefix});
    };
    console.error = function(...args) {
      ConsoleQuieter._logs.push({type: 'error', args, prefix: opts.prefix});
    };
  }
 
  static unmuteAndFlush() {
    console.log = ConsoleQuieter._consolelog;
    console.warn = ConsoleQuieter._consolewarn;
    console.error = ConsoleQuieter._consoleerror;
 
    ConsoleQuieter._logs.forEach(entry => {
      log.verbose(`${entry.prefix}-${entry.type}`, ...entry.args);
    });
    ConsoleQuieter._logs = [];
  }
}
 
ConsoleQuieter._consolelog = console.log.bind(console);
ConsoleQuieter._consolewarn = console.warn.bind(console);
ConsoleQuieter._consoleerror = console.error.bind(console);
 
module.exports = ConsoleQuieter;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/element.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/element.js

Statements: 8.33% (1 / 12)      Branches: 0% (0 / 6)      Functions: 0% (0 / 3)      Lines: 8.33% (1 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                                                                                                                                1    
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
class Element {
 
  constructor(element, driver) {
    if (!element || !driver) {
      throw Error('Driver and element required to create Element');
    }
    this.driver = driver;
    this.element = element;
  }
 
  /**
   * @param {!string} name Attribute name
   * @return {!Promise<?string>} The attribute value or null if not found
   */
  getAttribute(name) {
    return this.driver
      .sendCommand('DOM.getAttributes', {
        nodeId: this.element.nodeId
      })
      /**
       * @param {!{attributes: !Array<!string>}} resp The element attribute names & values are interleaved
       */
      .then(resp => {
        const attrIndex = resp.attributes.indexOf(name);
        if (attrIndex === -1) {
          return null;
        }
        return resp.attributes[attrIndex + 1];
      });
  }
 
  /**
   * @param {!string} propName Property name
   * @return {!Promise<?string>} The property value
   */
  getProperty(propName) {
    return this.driver
      .sendCommand('DOM.resolveNode', {
        nodeId: this.element.nodeId
      })
      .then(resp => {
        return this.driver.getObjectProperty(resp.object.objectId, propName);
      });
  }
}
 
module.exports = Element;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/empty-stub.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/empty-stub.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24                                          1    
/**
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
/**
 * Exports an empty object for when the module loading system needs *something*
 * to be loaded but it doesn't care what it is.
 */
module.exports = {};
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/emulation.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/emulation.js

Statements: 68.75% (22 / 32)      Branches: 100% (2 / 2)      Functions: 12.5% (1 / 8)      Lines: 70.97% (22 / 31)      Ignored: 7 statements, 1 function, 2 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152                                          1                                 1         1             1               1             1     1       1               1 1 1 1 1 1 1                                               1       1       1       1       1       1                     1                    
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
/**
 * Nexus 5X metrics adapted from emulated_devices/module.json
 */
const NEXUS5X_EMULATION_METRICS = {
  mobile: true,
  screenWidth: 412,
  screenHeight: 732,
  width: 412,
  height: 732,
  positionX: 0,
  positionY: 0,
  scale: 1,
  deviceScaleFactor: 2.625,
  fitWindow: false,
  screenOrientation: {
    angle: 0,
    type: 'portraitPrimary'
  }
};
 
const NEXUS5X_USERAGENT = {
  userAgent: 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5 Build/MRA58N) AppleWebKit/537.36' +
    '(KHTML, like Gecko) Chrome/52.0.2743.8 Mobile Safari/537.36'
};
 
const TYPICAL_MOBILE_THROTTLING_METRICS = {
  latency: 150, // 150ms
  downloadThroughput: Math.floor(1.6 * 1024 * 1024 / 8), // 1.6Mbps
  uploadThroughput: Math.floor(750 * 1024 / 8), // 750Kbps
  offline: false
};
 
const OFFLINE_METRICS = {
  offline: true,
  // values of 0 remove any active throttling. crbug.com/456324#c9
  latency: 0,
  downloadThroughput: 0,
  uploadThroughput: 0
};
 
const NO_THROTTLING_METRICS = {
  latency: 0,
  downloadThroughput: 0,
  uploadThroughput: 0,
  offline: false
};
 
const NO_CPU_THROTTLE_METRICS = {
  rate: 1
};
const CPU_THROTTLE_METRICS = {
  rate: 5
};
 
function enableNexus5X(driver) {
  /**
   * Finalizes touch emulation by enabling `"ontouchstart" in window` feature detect
   * to work. Messy hack, though copied verbatim from DevTools' emulation/TouchModel.js
   * where it's been working for years. addScriptToEvaluateOnLoad runs before any of the
   * page's JavaScript executes.
   */
  /* eslint-disable no-proto */ /* global window, document */ /* istanbul ignore next */
  const injectedTouchEventsFunction = function() {
    const touchEvents = ['ontouchstart', 'ontouchend', 'ontouchmove', 'ontouchcancel'];
    const recepients = [window.__proto__, document.__proto__];
    for (let i = 0; i < touchEvents.length; ++i) {
      for (let j = 0; j < recepients.length; ++j) {
        if (!(touchEvents[i] in recepients[j])) {
          Object.defineProperty(recepients[j], touchEvents[i], {
            value: null, writable: true, configurable: true, enumerable: true
          });
        }
      }
    }
  };
  /* eslint-enable */
 
  return Promise.all([
    driver.sendCommand('Emulation.setDeviceMetricsOverride', NEXUS5X_EMULATION_METRICS),
    // Network.enable must be called for UA overriding to work
    driver.sendCommand('Network.enable'),
    driver.sendCommand('Network.setUserAgentOverride', NEXUS5X_USERAGENT),
    driver.sendCommand('Emulation.setTouchEmulationEnabled', {
      enabled: true,
      configuration: 'mobile'
    }),
    driver.sendCommand('Page.addScriptToEvaluateOnLoad', {
      scriptSource: '(' + injectedTouchEventsFunction.toString() + ')()'
    })
  ]);
}
 
function enableNetworkThrottling(driver) {
  return driver.sendCommand('Network.emulateNetworkConditions', TYPICAL_MOBILE_THROTTLING_METRICS);
}
 
function disableNetworkThrottling(driver) {
  return driver.sendCommand('Network.emulateNetworkConditions', NO_THROTTLING_METRICS);
}
 
function goOffline(driver) {
  return driver.sendCommand('Network.emulateNetworkConditions', OFFLINE_METRICS);
}
 
function enableCPUThrottling(driver) {
  return driver.sendCommand('Emulation.setCPUThrottlingRate', CPU_THROTTLE_METRICS);
}
 
function disableCPUThrottling(driver) {
  return driver.sendCommand('Emulation.setCPUThrottlingRate', NO_CPU_THROTTLE_METRICS);
}
 
function getEmulationDesc() {
  const {latency, downloadThroughput, uploadThroughput} = TYPICAL_MOBILE_THROTTLING_METRICS;
  const byteToMbit = bytes => (bytes / 1024 / 1024 * 8).toFixed(1);
  return {
    'deviceEmulation': 'Nexus 5X',
    'cpuThrottling': `${CPU_THROTTLE_METRICS.rate}x slowdown`,
    'networkThrottling': `${latency}ms RTT, ${byteToMbit(downloadThroughput)}Mbps down, ` +
        `${byteToMbit(uploadThroughput)}Mbps up`
  };
}
 
module.exports = {
  enableNexus5X,
  enableNetworkThrottling,
  disableNetworkThrottling,
  enableCPUThrottling,
  disableCPUThrottling,
  goOffline,
  getEmulationDesc
};
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/event-helpers.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/event-helpers.js

Statements: 14.29% (3 / 21)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 14.29% (3 / 21)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86                                                      1                                                 1                                                       1          
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
/**
 * Adds line/col information to an event listener object along with a formatted
 * code snippet of violation.
 *
 * @param {!Object} listener A modified EventListener object as returned
 *     by the driver in the all events gatherer.
 * @return {!Object} A copy of the original listener object with the added
 *     properties.
 */
function addFormattedCodeSnippet(listener) {
  const handler = listener.handler ? listener.handler.description : '...';
  const objectName = listener.objectName.toLowerCase().replace('#document', 'document');
  return Object.assign({
    label: `line: ${listener.line}, col: ${listener.col}`,
    pre: `${objectName}.addEventListener('${listener.type}', ${handler})`
  }, listener);
}
 
/**
 * Groups event listeners under url/line/col "violation buckets".
 *
 * The listener gatherer returns a list of (url/line/col) src locations where
 * event handlers were attached to DOM nodes. This location is where
 * addEventListener was invoked, but it's not guaranteed to be where
 * the user's event handler was defined. An example is libraries, where the
 * user provides a callback and the library calls addEventListener (another
 * part of the codebase). Instead we map url/line/col/type to array of event
 * handlers so the user doesn't see a redundant list of url/line/col from the
 * same location.
 *
 * @param {!Array<!Object>} listeners Results from the event listener gatherer.
 * @return {!Array<{line: number, col: number, url: string, type: string, pre: string, label: string}>}
 *     A list of slimmed down listener objects.
 */
function groupCodeSnippetsByLocation(listeners) {
  const locToListenersMap = new Map();
  listeners.forEach(loc => {
    const key = JSON.stringify({line: loc.line, col: loc.col, url: loc.url, type: loc.type});
    if (locToListenersMap.has(key)) {
      locToListenersMap.get(key).push(loc);
    } else {
      locToListenersMap.set(key, [loc]);
    }
  });
 
  const results = [];
  locToListenersMap.forEach((listenersForLocation, key) => {
    const lineColUrlObj = JSON.parse(key);
    // Aggregate the code snippets.
    const codeSnippets = listenersForLocation.reduce((prev, loc) => {
      return prev + loc.pre.trim() + '\n\n';
    }, '');
    lineColUrlObj.pre = codeSnippets;
    // All listeners under this bucket have the same line/col. We use the first's
    // label as the label for all of them.
    lineColUrlObj.label = listenersForLocation[0].label;
    results.push(lineColUrlObj);
  });
 
  return results;
}
 
module.exports = {
  addFormattedCodeSnippet,
  groupCodeSnippetsByLocation
};
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/file-namer.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/file-namer.js

Statements: 38.46% (5 / 13)      Branches: 33.33% (3 / 9)      Functions: 0% (0 / 1)      Lines: 38.46% (5 / 13)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                                                  1                                 1 1 1   1          
/**
 * @license
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
/**
 * Generate a filenamePrefix of hostname_YYYY-MM-DD_HH-MM-SS
 * Date/time uses the local timezone, however Node has unreliable ICU
 * support, so we must construct a YYYY-MM-DD date format manually. :/
 * @param {!Object} results
 * @returns string
 */
function getFilenamePrefix(results) {
  // eslint-disable-next-line no-undef
  const hostname = new (URLConstructor || URL)(results.url).hostname;
  const date = (results.generatedTime && new Date(results.generatedTime)) || new Date();
 
  const timeStr = date.toLocaleTimeString('en-US', {hour12: false});
  const dateParts = date.toLocaleDateString('en-US', {
    year: 'numeric', month: '2-digit', day: '2-digit'
  }).split('/');
  dateParts.unshift(dateParts.pop());
  const dateStr = dateParts.join('-');
 
  const filenamePrefix = `${hostname}_${dateStr}_${timeStr}`;
  // replace characters that are unfriendly to filenames
  return filenamePrefix.replace(/[\/\?<>\\:\*\|":]/g, '-');
}
 
let URLConstructor;
Eif (typeof module !== 'undefined' && module.exports) {
  URLConstructor = require('./url-shim');
 
  module.exports = {
    getFilenamePrefix
  };
}
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/icons.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/icons.js

Statements: 15% (3 / 20)      Branches: 0% (0 / 10)      Functions: 0% (0 / 2)      Lines: 15.79% (3 / 19)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68                                            1                             1                                                 1          
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
/**
 * @param {!Manifest=} manifest
 * @return {boolean} Does the manifest have any icons?
 */
function doExist(manifest) {
  if (!manifest || !manifest.icons) {
    return false;
  }
  if (manifest.icons.value.length === 0) {
    return false;
  }
  return true;
}
 
/**
 * @param {number} sizeRequirement
 * @param {!Manifest} manifest
 * @return {!Array<string>} Value of satisfactory sizes (eg. ['192x192', '256x256'])
 */
function sizeAtLeast(sizeRequirement, manifest) {
  // An icon can be provided for a single size, or for multiple sizes.
  // To handle both, we flatten all found sizes into a single array.
  const iconValues = manifest.icons.value;
  const nestedSizes = iconValues.map(icon => icon.value.sizes.value);
  const flattenedSizes = [].concat(...nestedSizes);
 
  return flattenedSizes
      // First, filter out any undefined values, in case an icon was defined without a size
      .filter(size => typeof size === 'string')
      // discard sizes that are not AAxBB (eg. "any")
      .filter(size => /\d+x\d+/.test(size))
      .filter(size => {
        // Split the '24x24' strings into ['24','24'] arrays
        const sizeStrs = size.split(/x/i);
        // Cast the ['24','24'] strings into [24,24] numbers
        const sizeNums = [parseFloat(sizeStrs[0]), parseFloat(sizeStrs[1])];
        // Only keep sizes that are as big as our required size
        const areIconsBigEnough = sizeNums[0] >= sizeRequirement && sizeNums[1] >= sizeRequirement;
        // Square is required: https://code.google.com/p/chromium/codesearch#chromium/src/chrome/browser/manifest/manifest_icon_selector.cc&q=ManifestIconSelector::IconSizesContainsBiggerThanMinimumSize&sq=package:chromium
        const areIconsSquare = sizeNums[0] === sizeNums[1];
        return areIconsBigEnough && areIconsSquare;
      });
}
 
module.exports = {
  doExist,
  sizeAtLeast
};
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/log.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/log.js

Statements: 50% (30 / 60)      Branches: 28.85% (15 / 52)      Functions: 37.04% (10 / 27)      Lines: 50% (30 / 60)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220                                    1 1 1     1   1                   1                   5                               1 1         5 5       5 5 2 2   2   2       5       1                     1                                       3 3                         2 2                 1                         1                               1               1                                                                       1   1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const debug = require('debug');
const EventEmitter = require('events').EventEmitter;
const isWindows = process.platform === 'win32';
 
// process.browser is set when browserify'd via the `process` npm module
const isBrowser = process.browser;
 
const colors = {
  red: isBrowser ? 'crimson' : 1,
  yellow: isBrowser ? 'gold' : 3,
  cyan: isBrowser ? 'darkturquoise' : 6,
  green: isBrowser ? 'forestgreen' : 2,
  blue: isBrowser ? 'steelblue' : 4,
  magenta: isBrowser ? 'palevioletred' : 5
};
 
// whitelist non-red/yellow colors for debug()
debug.colors = [colors.cyan, colors.green, colors.blue, colors.magenta];
 
class Emitter extends EventEmitter {
  /**
   * Fires off all status updates. Listen with
   * `require('lib/log').events.addListener('status', callback)`
   * @param {string} title
   * @param {!Array<*>} argsArray
   */
  issueStatus(title, argsArray) {
    Iif (title === 'status' || title === 'statusEnd') {
      this.emit(title, [title, ...argsArray]);
    }
  }
 
  /**
   * Fires off all warnings. Listen with
   * `require('lib/log').events.addListener('warning', callback)`
   * @param {string} title
   * @param {!Array<*>} argsArray
   */
  issueWarning(title, argsArray) {
    this.emit('warning', [title, ...argsArray]);
  }
}
 
const loggersByTitle = {};
const loggingBufferColumns = 25;
 
class Log {
 
  static _logToStdErr(title, argsArray) {
    const log = Log.loggerfn(title);
    log(...argsArray);
  }
 
  static loggerfn(title) {
    let log = loggersByTitle[title];
    if (!log) {
      log = debug(title);
      loggersByTitle[title] = log;
      // errors with red, warnings with yellow.
      Iif (title.endsWith('error')) {
        log.color = colors.red;
      } else Iif (title.endsWith('warn')) {
        log.color = colors.yellow;
      }
    }
    return log;
  }
 
  static setLevel(level) {
    switch (level) {
      case 'silent':
        debug.enable('-*');
        break;
      case 'verbose':
        debug.enable('*');
        break;
      case 'error':
        debug.enable('-*, *:error');
        break;
      default:
        debug.enable('*, -*:verbose');
    }
  }
 
  /**
   * A simple formatting utility for event logging.
   * @param {string} prefix
   * @param {!Object} data A JSON-serializable object of event data to log.
   * @param {string=} level Optional logging level. Defaults to 'log'.
   */
  static formatProtocol(prefix, data, level) {
    const columns = (!process || process.browser) ? Infinity : process.stdout.columns;
    const maxLength = columns - data.method.length - prefix.length - loggingBufferColumns;
    // IO.read blacklisted here to avoid logging megabytes of trace data
    const snippet = (data.params && data.method !== 'IO.read') ?
      JSON.stringify(data.params).substr(0, maxLength) : '';
    Log._logToStdErr(`${prefix}:${level || ''}`, [data.method, snippet]);
  }
 
  static log(title, ...args) {
    Log.events.issueStatus(title, args);
    return Log._logToStdErr(title, args);
  }
 
  static warn(title, ...args) {
    Log.events.issueWarning(title, args);
    return Log._logToStdErr(`${title}:warn`, args);
  }
 
  static error(title, ...args) {
    return Log._logToStdErr(`${title}:error`, args);
  }
 
  static verbose(title, ...args) {
    Log.events.issueStatus(title, args);
    return Log._logToStdErr(`${title}:verbose`, args);
  }
 
  /**
   * Add surrounding escape sequences to turn a string green when logged.
   * @param {string} str
   * @return {string}
   */
  static greenify(str) {
    return `${Log.green}${str}${Log.reset}`;
  }
 
  /**
   * Add surrounding escape sequences to turn a string red when logged.
   * @param {string} str
   * @return {string}
   */
  static redify(str) {
    return `${Log.red}${str}${Log.reset}`;
  }
 
  static get green() {
    return '\x1B[32m';
  }
 
  static get red() {
    return '\x1B[31m';
  }
 
  static get yellow() {
    return '\x1b[33m';
  }
 
  static get purple() {
    return '\x1b[95m';
  }
 
  static get reset() {
    return '\x1B[0m';
  }
 
  static get bold() {
    return '\x1b[1m';
  }
 
  static get tick() {
    return isWindows ? '\u221A' : '✓';
  }
 
  static get cross() {
    return isWindows ? '\u00D7' : '✘';
  }
 
  static get whiteSmallSquare() {
    return isWindows ? '\u0387' : '▫';
  }
 
  static get heavyHorizontal() {
    return isWindows ? '\u2500' : '━';
  }
 
  static get heavyVertical() {
    return isWindows ? '\u2502 ' : '┃ ';
  }
 
  static get heavyUpAndRight() {
    return isWindows ? '\u2514' : '┗';
  }
 
  static get heavyVerticalAndRight() {
    return isWindows ? '\u251C' : '┣';
  }
 
  static get heavyDownAndHorizontal() {
    return isWindows ? '\u252C' : '┳';
  }
 
  static get doubleLightHorizontal() {
    return '──';
  }
}
 
Log.events = new Emitter();
 
module.exports = Log;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/manifest-parser.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/manifest-parser.js

Statements: 16.06% (22 / 137)      Branches: 0% (0 / 59)      Functions: 0% (0 / 16)      Lines: 16.18% (22 / 136)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401                                    1 1   1                   1   1                     1                                       1                                   1       1                   1                   1                                                                                         1                                   1                       1                                                                                           1                                                                       1                                                     1                                                                 1                                         1       1                     1                                                                             1    
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const URL = require('./url-shim');
const validateColor = require('./web-inspector').Color.parse;
 
const ALLOWED_DISPLAY_VALUES = [
  'fullscreen',
  'standalone',
  'minimal-ui',
  'browser'
];
/**
 * All display-mode fallbacks, including when unset, lead to default display mode 'browser'.
 * @see https://w3c.github.io/manifest/#dfn-default-display-mode
 */
const DEFAULT_DISPLAY_MODE = 'browser';
 
const ALLOWED_ORIENTATION_VALUES = [
  'any',
  'natural',
  'landscape',
  'portrait',
  'portrait-primary',
  'portrait-secondary',
  'landscape-primary',
  'landscape-secondary'
];
 
function parseString(raw, trim) {
  let value;
  let debugString;
 
  if (typeof raw === 'string') {
    value = trim ? raw.trim() : raw;
  } else {
    if (raw !== undefined) {
      debugString = 'ERROR: expected a string.';
    }
    value = undefined;
  }
 
  return {
    raw,
    value,
    debugString
  };
}
 
function parseColor(raw) {
  const color = parseString(raw);
 
  // Finished if color missing or not a string.
  if (color.value === undefined) {
    return color;
  }
 
  // Use DevTools's color parser to check CSS3 Color parsing.
  const validatedColor = validateColor(color.raw);
  if (!validatedColor) {
    color.value = undefined;
    color.debugString = 'ERROR: color parsing failed.';
  }
 
  return color;
}
 
function parseName(jsonInput) {
  return parseString(jsonInput.name, true);
}
 
function parseShortName(jsonInput) {
  return parseString(jsonInput.short_name, true);
}
 
/**
 * Returns whether the urls are of the same origin. See https://html.spec.whatwg.org/#same-origin
 * @param {string} url1
 * @param {string} url2
 * @return {boolean}
 */
function checkSameOrigin(url1, url2) {
  const parsed1 = new URL(url1);
  const parsed2 = new URL(url2);
 
  return parsed1.origin === parsed2.origin;
}
 
/**
 * https://w3c.github.io/manifest/#start_url-member
 */
function parseStartUrl(jsonInput, manifestUrl, documentUrl) {
  const raw = jsonInput.start_url;
 
  // 8.10(3) - discard the empty string and non-strings.
  if (raw === '') {
    return {
      raw,
      value: documentUrl,
      debugString: 'ERROR: start_url string empty'
    };
  }
  const parsedAsString = parseString(raw);
  if (!parsedAsString.value) {
    parsedAsString.value = documentUrl;
    return parsedAsString;
  }
 
  // 8.10(4) - construct URL with raw as input and manifestUrl as the base.
  let startUrl;
  try {
    startUrl = new URL(raw, manifestUrl).href;
  } catch (e) {
    // 8.10(5) - discard invalid URLs.
    return {
      raw,
      value: documentUrl,
      debugString: 'ERROR: invalid start_url relative to ${manifestUrl}'
    };
  }
 
  // 8.10(6) - discard start_urls that are not same origin as documentUrl.
  if (!checkSameOrigin(startUrl, documentUrl)) {
    return {
      raw,
      value: documentUrl,
      debugString: 'ERROR: start_url must be same-origin as document'
    };
  }
 
  return {
    raw,
    value: startUrl
  };
}
 
function parseDisplay(jsonInput) {
  const display = parseString(jsonInput.display, true);
 
  if (!display.value) {
    display.value = DEFAULT_DISPLAY_MODE;
    return display;
  }
 
  display.value = display.value.toLowerCase();
  if (!ALLOWED_DISPLAY_VALUES.includes(display.value)) {
    display.debugString = 'ERROR: \'display\' has invalid value ' + display.value +
        ` will fall back to ${DEFAULT_DISPLAY_MODE}.`;
    display.value = DEFAULT_DISPLAY_MODE;
  }
 
  return display;
}
 
function parseOrientation(jsonInput) {
  const orientation = parseString(jsonInput.orientation, true);
 
  if (orientation.value &&
      !ALLOWED_ORIENTATION_VALUES.includes(orientation.value.toLowerCase())) {
    orientation.value = undefined;
    orientation.debugString = 'ERROR: \'orientation\' has an invalid value, will be ignored.';
  }
 
  return orientation;
}
 
function parseIcon(raw, manifestUrl) {
  // 9.4(3)
  const src = parseString(raw.src, true);
  // 9.4(4) - discard if trimmed value is the empty string.
  if (src.value === '') {
    src.value = undefined;
  }
  if (src.value) {
    // 9.4(4) - construct URL with manifest URL as the base
    src.value = new URL(src.value, manifestUrl).href;
  }
 
  const type = parseString(raw.type, true);
 
  const density = {
    raw: raw.density,
    value: 1,
    debugString: undefined
  };
  if (density.raw !== undefined) {
    density.value = parseFloat(density.raw);
    if (isNaN(density.value) || !isFinite(density.value) || density.value <= 0) {
      density.value = 1;
      density.debugString = 'ERROR: icon density cannot be NaN, +∞, or less than or equal to +0.';
    }
  }
 
  const sizes = parseString(raw.sizes);
  if (sizes.value !== undefined) {
    const set = new Set();
    sizes.value.trim().split(/\s+/).forEach(size => set.add(size.toLowerCase()));
    sizes.value = set.size > 0 ? Array.from(set) : undefined;
  }
 
  return {
    raw,
    value: {
      src,
      type,
      density,
      sizes
    },
    debugString: undefined
  };
}
 
function parseIcons(jsonInput, manifestUrl) {
  const raw = jsonInput.icons;
 
  if (raw === undefined) {
    return {
      raw,
      value: [],
      debugString: undefined
    };
  }
 
  if (!Array.isArray(raw)) {
    return {
      raw,
      value: [],
      debugString: 'ERROR: \'icons\' expected to be an array but is not.'
    };
  }
 
  // TODO(bckenny): spec says to skip icons missing `src`, so debug messages on
  // individual icons are lost. Warn instead?
  const value = raw
    // 9.6(3)(1)
    .filter(icon => icon.src !== undefined)
    // 9.6(3)(2)(1)
    .map(icon => parseIcon(icon, manifestUrl))
    // 9.6(3)(2)(2)
    .filter(parsedIcon => parsedIcon.value.src.value !== undefined);
 
  return {
    raw,
    value,
    debugString: undefined
  };
}
 
function parseApplication(raw) {
  const platform = parseString(raw.platform, true);
  const id = parseString(raw.id, true);
 
  // 10.2.(2) and 10.2.(3)
  const appUrl = parseString(raw.url, true);
  if (appUrl.value) {
    try {
      // 10.2.(4) - attempt to construct URL.
      appUrl.value = new URL(appUrl.value).href;
    } catch (e) {
      appUrl.value = undefined;
      appUrl.debugString = 'ERROR: invalid application URL ${raw.url}';
    }
  }
 
  return {
    raw,
    value: {
      platform,
      id,
      url: appUrl
    },
    debugString: undefined
  };
}
 
function parseRelatedApplications(jsonInput) {
  const raw = jsonInput.related_applications;
 
  if (raw === undefined) {
    return {
      raw,
      value: undefined,
      debugString: undefined
    };
  }
 
  if (!Array.isArray(raw)) {
    return {
      raw,
      value: undefined,
      debugString: 'ERROR: \'related_applications\' expected to be an array but is not.'
    };
  }
 
  // TODO(bckenny): spec says to skip apps missing `platform`, so debug messages
  // on individual apps are lost. Warn instead?
  const value = raw
    .filter(application => !!application.platform)
    .map(parseApplication)
    .filter(parsedApp => !!parsedApp.value.id.value || !!parsedApp.value.url.value);
 
  return {
    raw,
    value,
    debugString: undefined
  };
}
 
function parsePreferRelatedApplications(jsonInput) {
  const raw = jsonInput.prefer_related_applications;
  let value;
  let debugString;
 
  if (typeof raw === 'boolean') {
    value = raw;
  } else {
    if (raw !== undefined) {
      debugString = 'ERROR: \'prefer_related_applications\' expected to be a boolean.';
    }
    value = undefined;
  }
 
  return {
    raw,
    value,
    debugString
  };
}
 
function parseThemeColor(jsonInput) {
  return parseColor(jsonInput.theme_color);
}
 
function parseBackgroundColor(jsonInput) {
  return parseColor(jsonInput.background_color);
}
 
/**
 * Parse a manifest from the given inputs.
 * @param {string} string Manifest JSON string.
 * @param {string} manifestUrl URL of manifest file.
 * @param {string} documentUrl URL of document containing manifest link element.
 * @return {!ManifestNode<(!Manifest|undefined)>}
 */
function parse(string, manifestUrl, documentUrl) {
  if (manifestUrl === undefined || documentUrl === undefined) {
    throw new Error('Manifest and document URLs required for manifest parsing.');
  }
 
  let jsonInput;
 
  try {
    jsonInput = JSON.parse(string);
  } catch (e) {
    return {
      raw: string,
      value: undefined,
      debugString: 'ERROR: file isn\'t valid JSON: ' + e
    };
  }
 
  /* eslint-disable camelcase */
  const manifest = {
    name: parseName(jsonInput),
    short_name: parseShortName(jsonInput),
    start_url: parseStartUrl(jsonInput, manifestUrl, documentUrl),
    display: parseDisplay(jsonInput),
    orientation: parseOrientation(jsonInput),
    icons: parseIcons(jsonInput, manifestUrl),
    related_applications: parseRelatedApplications(jsonInput),
    prefer_related_applications: parsePreferRelatedApplications(jsonInput),
    theme_color: parseThemeColor(jsonInput),
    background_color: parseBackgroundColor(jsonInput)
  };
  /* eslint-enable camelcase */
 
  return {
    raw: string,
    value: manifest,
    debugString: undefined
  };
}
 
module.exports = parse;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/network-recorder.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/network-recorder.js

Statements: 7.27% (4 / 55)      Branches: 0% (0 / 12)      Functions: 0% (0 / 14)      Lines: 7.27% (4 / 55)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173                                    1 1 1                                                                                                                                                                                                                                                                                                           1    
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const NetworkManager = require('./web-inspector').NetworkManager;
const EventEmitter = require('events').EventEmitter;
const log = require('../lib/log.js');
 
class NetworkRecorder extends EventEmitter {
  constructor(recordArray) {
    super();
 
    this._records = recordArray;
    this.networkManager = NetworkManager.createWithFakeTarget();
 
    this.startedRequestCount = 0;
    this.finishedRequestCount = 0;
 
    this.networkManager.addEventListener(this.EventTypes.RequestStarted,
        this.onRequestStarted.bind(this));
    this.networkManager.addEventListener(this.EventTypes.RequestFinished,
        this.onRequestFinished.bind(this));
 
    this.onRequestWillBeSent = this.onRequestWillBeSent.bind(this);
    this.onRequestServedFromCache = this.onRequestServedFromCache.bind(this);
    this.onResponseReceived = this.onResponseReceived.bind(this);
    this.onDataReceived = this.onDataReceived.bind(this);
    this.onLoadingFinished = this.onLoadingFinished.bind(this);
    this.onLoadingFailed = this.onLoadingFailed.bind(this);
    this.onResourceChangedPriority = this.onResourceChangedPriority.bind(this);
  }
 
  get EventTypes() {
    return NetworkManager.Events;
  }
 
  activeRequestCount() {
    return this.startedRequestCount - this.finishedRequestCount;
  }
 
  isIdle() {
    return this.activeRequestCount() === 0;
  }
 
  /**
   * Listener for the NetworkManager's RequestStarted event, which includes both
   * web socket and normal request creation.
   * @private
   */
  onRequestStarted() {
    this.startedRequestCount++;
 
    const activeCount = this.activeRequestCount();
    log.verbose('NetworkRecorder', `Request started. ${activeCount} requests in progress` +
        ` (${this.startedRequestCount} started and ${this.finishedRequestCount} finished).`);
 
    // If only one request in progress, emit event that we've transitioned from
    // idle to busy.
    if (activeCount === 1) {
      this.emit('networkbusy');
    }
  }
 
  /**
   * Listener for the NetworkManager's RequestFinished event, which includes
   * request finish, failure, and redirect, as well as the closing of web
   * sockets.
   * @param {!WebInspector.NetworkRequest} request
   * @private
   */
  onRequestFinished(request) {
    this.finishedRequestCount++;
    this._records.push(request.data);
    this.emit('requestloaded', request.data);
 
    const activeCount = this.activeRequestCount();
    log.verbose('NetworkRecorder', `Request finished. ${activeCount} requests in progress` +
        ` (${this.startedRequestCount} started and ${this.finishedRequestCount} finished).`);
 
    // If no requests in progress, emit event that we've transitioned from busy
    // to idle.
    if (this.isIdle()) {
      this.emit('networkidle');
    }
  }
 
  // There are a few differences between the debugging protocol naming and
  // the parameter naming used in NetworkManager. These are noted below.
 
  onRequestWillBeSent(data) {
    // NOTE: data.timestamp -> time, data.type -> resourceType
    this.networkManager._dispatcher.requestWillBeSent(data.requestId,
        data.frameId, data.loaderId, data.documentURL, data.request,
        data.timestamp, data.wallTime, data.initiator, data.redirectResponse,
        data.type);
  }
 
  onRequestServedFromCache(data) {
    this.networkManager._dispatcher.requestServedFromCache(data.requestId);
  }
 
  onResponseReceived(data) {
    // NOTE: data.timestamp -> time, data.type -> resourceType
    this.networkManager._dispatcher.responseReceived(data.requestId,
        data.frameId, data.loaderId, data.timestamp, data.type, data.response);
  }
 
  onDataReceived(data) {
    // NOTE: data.timestamp -> time
    this.networkManager._dispatcher.dataReceived(data.requestId, data.timestamp,
        data.dataLength, data.encodedDataLength);
  }
 
  onLoadingFinished(data) {
    // NOTE: data.timestamp -> finishTime
    this.networkManager._dispatcher.loadingFinished(data.requestId,
        data.timestamp, data.encodedDataLength);
  }
 
  onLoadingFailed(data) {
    // NOTE: data.timestamp -> time, data.type -> resourceType,
    // data.errorText -> localizedDescription
    this.networkManager._dispatcher.loadingFailed(data.requestId,
        data.timestamp, data.type, data.errorText, data.canceled,
        data.blockedReason);
  }
 
  onResourceChangedPriority(data) {
    this.networkManager._dispatcher.resourceChangedPriority(data.requestId,
        data.newPriority, data.timestamp);
  }
 
  static recordsFromLogs(logs) {
    const records = [];
    const nr = new NetworkRecorder(records);
    const dispatcher = method => {
      switch (method) {
        case 'Network.requestWillBeSent': return nr.onRequestWillBeSent;
        case 'Network.requestServedFromCache': return nr.onRequestServedFromCache;
        case 'Network.responseReceived': return nr.onResponseReceived;
        case 'Network.dataReceived': return nr.onDataReceived;
        case 'Network.loadingFinished': return nr.onLoadingFinished;
        case 'Network.loadingFailed': return nr.onLoadingFailed;
        case 'Network.resourceChangedPriority': return nr.onResourceChangedPriority;
        default: return () => {};
      }
    };
 
    logs.forEach(networkEvent => {
      dispatcher(networkEvent.method)(networkEvent.params);
    });
 
    return records;
  }
}
 
module.exports = NetworkRecorder;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/styles-helpers.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/styles-helpers.js

Statements: 8% (4 / 50)      Branches: 0% (0 / 32)      Functions: 0% (0 / 3)      Lines: 8.33% (4 / 48)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134                                                            1                                                                                           1                                                                             1                       1            
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
/**
 * Filters a list of stylesheets for usage of a CSS property name, value,
 * or name/value pair.
 *
 * @param {!Array} stylesheets A list of stylesheets used by the page.
 * @param {string|Array<string>=} propName Optional name of the CSS property/properties to filter
 *     results on. If propVal is not specified, all stylesheets that use the property are
 *     returned. Otherwise, stylesheets that use the propName: propVal are returned.
 * @param {string|Array<string>=} propVal Optional value of the CSS property/propertys to filter
 *     results on.
 * @return {!Array} A list of stylesheets that use the CSS property.
 */
function filterStylesheetsByUsage(stylesheets, propName, propVal) {
  if (!propName && !propVal) {
    return [];
  }
  // Create deep clone of arrays so multiple calls to filterStylesheetsByUsage
  // don't alter the original artifacts in stylesheets arg.
  const deepClone = stylesheets.map(sheet => Object.assign({}, sheet));
 
  return deepClone.filter(s => {
    if (s.isDuplicate) {
      return false;
    }
 
    s.parsedContent = s.parsedContent.filter(item => {
      let usedName = '';
      let usedVal = '';
      // Prevent includes call on null value
      if (propName) {
        propName = Array.isArray(propName) ? propName : [propName];
        usedName = propName.includes(item.property.name);
      }
      if (propVal) {
        propVal = Array.isArray(propVal) ? propVal : [propVal];
        usedVal = propVal.includes(item.property.val);
      }
      // Allow search by css property name, a value, or name/value pair.
      if (propName && !propVal) {
        return usedName;
      } else if (!propName && propVal) {
        return usedVal;
      } else if (propName && propVal) {
        return usedName && usedVal;
      }
      return false;
    });
    return s.parsedContent.length > 0;
  });
}
 
/**
 * Returns a formatted snippet of CSS and the location of its use.
 *
 * @param {!string} content CSS text content.
 * @param {!Object} parsedContent The parsed version content.
 * @return {{styleRule: string, location: string}} Formatted output.
 */
function getFormattedStyleRule(content, parsedContent) {
  const lines = content.split('\n');
 
  const declarationRange = parsedContent.declarationRange;
 
  const startLine = declarationRange.startLine;
  const endLine = declarationRange.endLine;
  const start = declarationRange.startColumn;
  const end = declarationRange.endColumn;
 
  let rule;
  if (startLine === endLine) {
    rule = lines[startLine].substring(start, end);
  } else {
    // If css property value spans multiple lines, include all of them so it's
    // obvious where the value was used.
    rule = lines.slice(startLine, endLine + 1).reduce((prev, line) => {
      prev.push(line);
      return prev;
    }, []).join('\n');
  }
 
  const block = parsedContent.selector + ' {\n' +
      `  ${rule.trim()}\n` +
      '}';
 
  return {
    styleRule: block.trim(),
    startLine,
    location: `${start}:${end}`
  };
}
 
/**
 * Returns an array of all CSS prefixes and the default CSS style names.
 *
 * @param {string|Array<string>=} propNames CSS property names.
 * @return {Array<string>=} CSS property names with and without vendor prefixes.
 */
function addVendorPrefixes(propsNames) {
  const vendorPrefixes = ['-o-', '-ms-', '-moz-', '-webkit-'];
  propsNames = Array.isArray(propsNames) ? propsNames : [propsNames];
  let propsNamesWithPrefixes = propsNames;
  // Map vendorPrefixes to propsNames
  for (const prefix of vendorPrefixes) {
    const temp = propsNames.map(propName => `${prefix}${propName}`);
    propsNamesWithPrefixes = propsNamesWithPrefixes.concat(temp);
  }
  // Add original propNames
  return propsNamesWithPrefixes;
}
module.exports = {
  filterStylesheetsByUsage,
  getFormattedStyleRule,
  addVendorPrefixes
};
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/url-shim.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/url-shim.js

Statements: 18% (9 / 50)      Branches: 11.11% (3 / 27)      Functions: 0% (0 / 5)      Lines: 18.37% (9 / 49)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154                                                  1       1   1               1                           1                         1                                                                                                                           1                     1                       1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
/**
 * URL shim so we keep our code DRY
 */
 
'use strict';
 
/* global self */
 
const ELLIPSIS = '\u2026';
 
// TODO: Add back node require('url').URL parsing when bug is resolved:
// https://github.com/GoogleChrome/lighthouse/issues/1186
const URL = (typeof self !== 'undefined' && self.URL) || require('whatwg-url').URL;
 
URL.INVALID_URL_DEBUG_STRING =
    'Lighthouse was unable to determine the URL of some script executions. ' +
    'It\'s possible a Chrome extension or other eval\'d code is the source.';
 
/**
 * @param {string} url
 * @return {boolean}
 */
URL.isValid = function isValid(url) {
  try {
    new URL(url);
    return true;
  } catch (e) {
    return false;
  }
};
 
/**
 * @param {string} urlA
 * @param {string} urlB
 * @return {boolean}
 */
URL.hostsMatch = function hostsMatch(urlA, urlB) {
  try {
    return new URL(urlA).host === new URL(urlB).host;
  } catch (e) {
    return false;
  }
};
 
/**
 * @param {string} url
 * @param {{numPathParts: number, preserveQuery: boolean, preserveHost: boolean}=} options
 * @return {string}
 */
URL.getDisplayName = function getDisplayName(url, options) {
  options = Object.assign({
    numPathParts: 2,
    preserveQuery: false,
    preserveHost: false,
  }, options);
 
  const parsed = new URL(url);
 
  let name;
 
  if (parsed.protocol === 'about:' || parsed.protocol === 'data:') {
    // Handle 'about:*' and 'data:*' URLs specially since they have no path.
    name = parsed.href;
  } else {
    name = parsed.pathname;
    const parts = name.split('/');
    if (options.numPathParts && parts.length > options.numPathParts) {
      name = ELLIPSIS + parts.slice(-1 * options.numPathParts).join('/');
    }
 
    if (options.preserveHost) {
      name = `${parsed.host}/${name.replace(/^\//, '')}`;
    }
    if (options.preserveQuery) {
      name = `${name}${parsed.search}`;
    }
  }
 
  const MAX_LENGTH = 64;
  // Always elide hash
  name = name.replace(/([a-f0-9]{7})[a-f0-9]{13}[a-f0-9]*/g, `$1${ELLIPSIS}`);
 
  // Elide query params first
  if (name.length > MAX_LENGTH && name.includes('?')) {
    // Try to leave the first query parameter intact
    name = name.replace(/\?([^=]*)(=)?.*/, `?$1$2${ELLIPSIS}`);
 
    // Remove it all if it's still too long
    if (name.length > MAX_LENGTH) {
      name = name.replace(/\?.*/, `?${ELLIPSIS}`);
    }
  }
 
  // Elide too long names next
  if (name.length > MAX_LENGTH) {
    const dotIndex = name.lastIndexOf('.');
    if (dotIndex >= 0) {
      name = name.slice(0, MAX_LENGTH - 1 - (name.length - dotIndex)) +
          // Show file extension
          `${ELLIPSIS}${name.slice(dotIndex)}`;
    } else {
      name = name.slice(0, MAX_LENGTH - 1) + ELLIPSIS;
    }
  }
 
  return name;
};
 
// There is fancy URL rewriting logic for the chrome://settings page that we need to work around.
// Why? Special handling was added by Chrome team to allow a pushState transition between chrome:// pages.
// As a result, the network URL (chrome://chrome/settings/) doesn't match the final document URL (chrome://settings/).
function rewriteChromeInternalUrl(url) {
  if (!url.startsWith('chrome://')) return url;
  return url.replace(/^chrome:\/\/chrome\//, 'chrome://');
}
 
/**
 * Determine if url1 equals url2, ignoring URL fragments.
 * @param {string} url1
 * @param {string} url2
 * @return {boolean}
 */
URL.equalWithExcludedFragments = function(url1, url2) {
  [url1, url2] = [url1, url2].map(rewriteChromeInternalUrl);
 
  url1 = new URL(url1);
  url1.hash = '';
 
  url2 = new URL(url2);
  url2.hash = '';
 
  return url1.href === url2.href;
};
 
module.exports = URL;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/web-inspector.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/web-inspector.js

Statements: 62.26% (66 / 106)      Branches: 20% (3 / 15)      Functions: 2.63% (1 / 38)      Lines: 62.26% (66 / 106)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303                                            1 1           1 1     1 1     1 1                   1                     1 1   1       1 1 1                                       1         1                                           1                     1                                   1 1 1 1 1 1 1 1 1     1       1                   1     1 1 1 1 1   1 1 1 1 1 1 1 1 1 1 1 1 1 1 1     1 1           1 1     1     1         1           1                             1           1                                                               1 1 1     1                                         1      
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
/**
 * Stubbery to allow portions of the DevTools frontend to be used in lighthouse. `WebInspector`
 * technically lives on the global object but should be accessed through a normal `require` call.
 */
module.exports = (function() {
  Iif (global.WebInspector) {
    return global.WebInspector;
  }
 
  // Global pollution.
  // Check below is to make it worker-friendly where global is worker's self.
  Eif (global.self !== global) {
    global.self = global;
  }
 
  Eif (typeof global.window === 'undefined') {
    global.window = global;
  }
 
  global.Runtime = {};
  global.Runtime.experiments = {
    isEnabled(experimentName) {
      switch (experimentName) {
        case 'timelineLatencyInfo':
          return true;
        default:
          return false;
      }
    }
  };
  global.Runtime.queryParam = function(arg) {
    switch (arg) {
      case 'remoteFrontend':
        return false;
      case 'ws':
        return false;
      default:
        throw Error('Mock queryParam case not implemented.');
    }
  };
 
  global.TreeElement = {};
  global.WorkerRuntime = {};
 
  global.Protocol = {
    Agents() {}
  };
 
  global.WebInspector = {};
  const WebInspector = global.WebInspector;
  WebInspector._moduleSettings = {
    cacheDisabled: {
      addChangeListener() {},
      get() {
        return false;
      }
    },
    monitoringXHREnabled: {
      addChangeListener() {},
      get() {
        return false;
      }
    },
    showNativeFunctionsInJSProfile: {
      addChangeListener() {},
      get() {
        return true;
      }
    }
  };
  WebInspector.moduleSetting = function(settingName) {
    return this._moduleSettings[settingName];
  };
 
  // Enum from chromium//src/third_party/WebKit/Source/core/loader/MixedContentChecker.h
  global.NetworkAgent = {
    RequestMixedContentType: {
      Blockable: 'blockable',
      OptionallyBlockable: 'optionally-blockable',
      None: 'none'
    },
    BlockedReason: {
      CSP: 'csp',
      MixedContent: 'mixed-content',
      Origin: 'origin',
      Inspector: 'inspector',
      Other: 'other'
    },
    InitiatorType: {
      Other: 'other',
      Parser: 'parser',
      Redirect: 'redirect',
      Script: 'script'
    }
  };
 
  // Enum from SecurityState enum in protocol's Security domain
  global.SecurityAgent = {
    SecurityState: {
      Unknown: 'unknown',
      Neutral: 'neutral',
      Insecure: 'insecure',
      Warning: 'warning',
      Secure: 'secure',
      Info: 'info'
    }
  };
  // From https://chromium.googlesource.com/chromium/src/third_party/WebKit/Source/devtools/+/master/protocol.json#93
  global.PageAgent = {
    ResourceType: {
      Document: 'document',
      Stylesheet: 'stylesheet',
      Image: 'image',
      Media: 'media',
      Font: 'font',
      Script: 'script',
      TextTrack: 'texttrack',
      XHR: 'xhr',
      Fetch: 'fetch',
      EventSource: 'eventsource',
      WebSocket: 'websocket',
      Manifest: 'manifest',
      Other: 'other'
    }
  };
  // Dependencies for network-recorder
  require('chrome-devtools-frontend/front_end/common/Object.js');
  require('chrome-devtools-frontend/front_end/common/ParsedURL.js');
  require('chrome-devtools-frontend/front_end/common/ResourceType.js');
  require('chrome-devtools-frontend/front_end/common/UIString.js');
  require('chrome-devtools-frontend/front_end/platform/utilities.js');
  require('chrome-devtools-frontend/front_end/sdk/Target.js');
  require('chrome-devtools-frontend/front_end/sdk/TargetManager.js');
  require('chrome-devtools-frontend/front_end/sdk/NetworkManager.js');
  require('chrome-devtools-frontend/front_end/sdk/NetworkRequest.js');
 
  // Dependencies for timeline-model
  WebInspector.targetManager = {
    observeTargets() { },
    addEventListener() { }
  };
  WebInspector.settings = {
    createSetting() {
      return {
        get() {
          return false;
        },
        addChangeListener() {}
      };
    }
  };
  WebInspector.console = {
    error() {}
  };
  WebInspector.VBox = function() {};
  WebInspector.HBox = function() {};
  WebInspector.ViewportDataGrid = function() {};
  WebInspector.ViewportDataGridNode = function() {};
  global.WorkerRuntime.Worker = function() {};
 
  require('chrome-devtools-frontend/front_end/common/SegmentedRange.js');
  require('chrome-devtools-frontend/front_end/bindings/TempFile.js');
  require('chrome-devtools-frontend/front_end/sdk/TracingModel.js');
  require('chrome-devtools-frontend/front_end/sdk/ProfileTreeModel.js');
  require('chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js');
  require('chrome-devtools-frontend/front_end/timeline_model/TimelineJSProfile.js');
  require('chrome-devtools-frontend/front_end/sdk/CPUProfileDataModel.js');
  require('chrome-devtools-frontend/front_end/timeline_model/LayerTreeModel.js');
  require('chrome-devtools-frontend/front_end/timeline_model/TimelineModel.js');
  require('chrome-devtools-frontend/front_end/ui_lazy/SortableDataGrid.js');
  require('chrome-devtools-frontend/front_end/timeline/TimelineTreeView.js');
  require('chrome-devtools-frontend/front_end/timeline_model/TimelineProfileTree.js');
  require('chrome-devtools-frontend/front_end/components_lazy/FilmStripModel.js');
  require('chrome-devtools-frontend/front_end/timeline_model/TimelineIRModel.js');
  require('chrome-devtools-frontend/front_end/timeline_model/TimelineFrameModel.js');
 
  // DevTools makes a few assumptions about using backing storage to hold traces.
  WebInspector.DeferredTempFile = function() {};
  WebInspector.DeferredTempFile.prototype = {
    write: function() {},
    finishWriting: function() {}
  };
 
  // Mock for WebInspector code that writes to console.
  WebInspector.ConsoleMessage = function() {};
  WebInspector.ConsoleMessage.MessageSource = {
    Network: 'network'
  };
  WebInspector.ConsoleMessage.MessageLevel = {
    Log: 'log'
  };
  WebInspector.ConsoleMessage.MessageType = {
    Log: 'log'
  };
 
  // Mock NetworkLog
  WebInspector.NetworkLog = function(target) {
    this._requests = new Map();
    target.networkManager.addEventListener(
      WebInspector.NetworkManager.Events.RequestStarted, this._onRequestStarted, this);
  };
 
  WebInspector.NetworkLog.prototype = {
    requestForURL: function(url) {
      return this._requests.get(url) || null;
    },
 
    _onRequestStarted: function(event) {
      const request = event.data;
      if (this._requests.has(request.url)) {
        return;
      }
      this._requests.set(request.url, request);
    }
  };
 
  // Dependencies for color parsing.
  require('chrome-devtools-frontend/front_end/common/Color.js');
 
  /**
   * Creates a new WebInspector NetworkManager using a mocked Target.
   * @return {!WebInspector.NetworkManager}
   */
  WebInspector.NetworkManager.createWithFakeTarget = function() {
    // Mocked-up WebInspector Target for NetworkManager
    const fakeNetworkAgent = {
      enable() {}
    };
    const fakeConsoleModel = {
      addMessage() {},
      target() {}
    };
    const fakeTarget = {
      _modelByConstructor: new Map(),
      get consoleModel() {
        return fakeConsoleModel;
      },
      networkAgent() {
        return fakeNetworkAgent;
      },
      registerNetworkDispatcher() { },
      model() { }
    };
 
    fakeTarget.networkManager = new WebInspector.NetworkManager(fakeTarget);
    fakeTarget.networkLog = new WebInspector.NetworkLog(fakeTarget);
 
    WebInspector.NetworkLog.fromTarget = () => {
      return fakeTarget.networkLog;
    };
 
    return fakeTarget.networkManager;
  };
 
  // Dependencies for CSS parsing.
  require('chrome-devtools-frontend/front_end/common/TextRange.js');
  const gonzales = require('chrome-devtools-frontend/front_end/gonzales/gonzales-scss.js');
  require('chrome-devtools-frontend/front_end/gonzales/SCSSParser.js');
 
  // Mostly taken from from chrome-devtools-frontend/front_end/gonzales/SCSSParser.js.
  WebInspector.SCSSParser.prototype.parse = function(content) {
    let ast = null;
    try {
      ast = gonzales.parse(content, {syntax: 'css'});
    } catch (e) {
      return {error: e};
    }
 
    /** @type {!{properties: !Array<!Gonzales.Node>, node: !Gonzales.Node}} */
    const rootBlock = {
      properties: [],
      node: ast
    };
    /** @type {!Array<!{properties: !Array<!Gonzales.Node>, node: !Gonzales.Node}>} */
    const blocks = [rootBlock];
    ast.selectors = [];
    WebInspector.SCSSParser.extractNodes(ast, blocks, rootBlock);
 
    return ast;
  };
 
  return WebInspector;
})();
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/traces/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/traces/

Statements: 12.5% (19 / 152)      Branches: 9.62% (5 / 52)      Functions: 6.25% (1 / 16)      Lines: 12.84% (19 / 148)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/traces/
File Statements Branches Functions Lines
pwmetrics-events.js 3.33% (2 / 60) 0% (0 / 17) 0% (0 / 6) 3.45% (2 / 58)
tracing-processor.js 18.48% (17 / 92) 14.29% (5 / 35) 10% (1 / 10) 18.89% (17 / 90)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/traces/pwmetrics-events.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/traces/pwmetrics-events.js

Statements: 3.33% (2 / 60)      Branches: 0% (0 / 17)      Functions: 0% (0 / 6)      Lines: 3.45% (2 / 58)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208                                    1                                                                                                                                                                                                                                                                                                                                                                                     1    
/**
 * @license
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
const log = require('../../../lighthouse-core/lib/log.js');
 
class Metrics {
 
  constructor(traceEvents, auditResults) {
    this._traceEvents = traceEvents;
    this._auditResults = auditResults;
  }
 
  /**
   * Returns simplified representation of all metrics
   * @return {!Array<{getTs: Function, id: string, name: string}>} metrics to consider
   */
  static get metricsDefinitions() {
    return [
      {
        name: 'Navigation Start',
        id: 'navstart',
        getTs: auditResults => {
          const fmpExt = auditResults['first-meaningful-paint'].extendedInfo;
          return fmpExt.value.timestamps.navStart;
        }
      },
      {
        name: 'First Contentful Paint',
        id: 'ttfcp',
        getTs: auditResults => {
          const fmpExt = auditResults['first-meaningful-paint'].extendedInfo;
          return fmpExt.value.timestamps.fCP;
        }
      },
      {
        name: 'First Meaningful Paint',
        id: 'ttfmp',
        getTs: auditResults => {
          const fmpExt = auditResults['first-meaningful-paint'].extendedInfo;
          return fmpExt.value.timestamps.fMP;
        }
      },
      {
        name: 'Perceptual Speed Index',
        id: 'psi',
        getTs: auditResults => {
          const siExt = auditResults['speed-index-metric'].extendedInfo;
          return siExt.value.timestamps.perceptualSpeedIndex;
        }
      },
      {
        name: 'First Visual Change',
        id: 'fv',
        getTs: auditResults => {
          const siExt = auditResults['speed-index-metric'].extendedInfo;
          return siExt.value.timestamps.firstVisualChange;
        }
      },
      {
        name: 'Visually Complete 85%',
        id: 'vc85',
        getTs: auditResults => {
          const siExt = auditResults['time-to-interactive'].extendedInfo;
          return siExt.value.timestamps.visuallyReady;
        }
      },
      {
        name: 'Visually Complete 100%',
        id: 'vc100',
        getTs: auditResults => {
          const siExt = auditResults['speed-index-metric'].extendedInfo;
          return siExt.value.timestamps.visuallyComplete;
        }
      },
      {
        name: 'Time to Interactive',
        id: 'tti',
        getTs: auditResults => {
          const ttiExt = auditResults['time-to-interactive'].extendedInfo;
          return ttiExt.value.timestamps.timeToInteractive;
        }
      }
    ];
  }
 
  /**
   * Returns simplified representation of all metrics' timestamps from monotonic clock
   * @return {!Array<{ts: number, id: string, name: string}>} metrics to consider
   */
  gatherMetrics() {
    const metricDfns = Metrics.metricsDefinitions;
    const resolvedMetrics = [];
    metricDfns.forEach(metric => {
      // try/catch in case auditResults is missing a particular audit result
      try {
        resolvedMetrics.push({
          id: metric.id,
          name: metric.name,
          ts: metric.getTs(this._auditResults)
        });
      } catch (e) {
        log.error('pwmetrics-events', `${metric.name} timestamp not found: ${e.message}`);
      }
    });
    return resolvedMetrics;
  }
 
  /**
   * Getter for our navigationStart trace event
   */
  getNavigationStartEvt() {
    if (!this._navigationStartEvt) {
      const filteredEvents = this._traceEvents.filter(e => {
        return e.name === 'TracingStartedInPage' || e.cat === 'blink.user_timing';
      });
 
      const tracingStartedEvt = filteredEvents.filter(e => e.name === 'TracingStartedInPage')[0];
      const navigationStartEvt = filteredEvents.filter(e => {
        return e.name === 'navigationStart' &&
            e.pid === tracingStartedEvt.pid && e.tid === tracingStartedEvt.tid;
      })[0];
      this._navigationStartEvt = navigationStartEvt;
    }
    return this._navigationStartEvt;
  }
 
 
  /**
   * Constructs performance.measure trace events, which have start/end events as follows:
   *     { "pid": 89922,"tid":1295,"ts":77176783452,"ph":"b","cat":"blink.user_timing","name":"innermeasure","args":{},"tts":1257886,"id":"0xe66c67"}
   *     { "pid": 89922,"tid":1295,"ts":77176882592,"ph":"e","cat":"blink.user_timing","name":"innermeasure","args":{},"tts":1257898,"id":"0xe66c67"}
   * @param {{ts: number, id: string, name: string}} metric
   * @param {{ts: number, id: string, name: string}} navStart
   * @return {!Array} Pair of trace events (start/end)
   */
  synthesizeEventPair(metric, navStart) {
    // We'll masquerade our fake events to look mostly like navigationStart
    const eventBase = {
      pid: this.getNavigationStartEvt().pid,
      tid: this.getNavigationStartEvt().tid,
      cat: 'blink.user_timing',
      name: metric.name,
      args: {},
      // randomized id is same for the pair
      id: `0x${((Math.random() * 1000000) | 0).toString(16)}`
    };
    const fakeMeasureStartEvent = Object.assign({}, eventBase, {
      ts: navStart.ts,
      ph: 'b'
    });
    const fakeMeasureEndEvent = Object.assign({}, eventBase, {
      ts: metric.ts,
      ph: 'e',
    });
    return [fakeMeasureStartEvent, fakeMeasureEndEvent];
  }
 
  /**
   * @returns {!Array} User timing raw trace event pairs
   */
  generateFakeEvents() {
    const fakeEvents = [];
    const metrics = this.gatherMetrics();
    if (metrics.length === 0) {
      log.error('metrics-events', 'Metrics collection had errors, not synthetizing trace events');
      return [];
    }
 
    // confirm our navStart's correctly match
    const navStartEvt = metrics.find(e => e.id === 'navstart');
    if (!navStartEvt || this.getNavigationStartEvt().ts !== navStartEvt.ts) {
      log.error('pwmetrics-events', 'Reference navigationStart doesn\'t match fMP\'s navStart');
      return [];
    }
 
    metrics.forEach(metric => {
      if (metric.id === 'navstart') {
        return;
      }
      if (!metric.ts) {
        log.error('pwmetrics-events', `(${metric.name}) missing timestamp. Skipping…`);
        return;
      }
      log.verbose('pwmetrics-events', `Sythesizing trace events for ${metric.name}`);
      fakeEvents.push(...this.synthesizeEventPair(metric, navStartEvt));
    });
    return fakeEvents;
  }
}
 
module.exports = Metrics;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/traces/tracing-processor.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/lib/traces/tracing-processor.js

Statements: 18.48% (17 / 92)      Branches: 14.29% (5 / 35)      Functions: 10% (1 / 10)      Lines: 18.89% (17 / 90)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278                                      1           1             1 1 9     1 1 1 1 2 1   1     1 1       1 1                                                                                                                                                                                                                                                                                                                                                                                                                                                           1    
/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
'use strict';
 
Iif (typeof global.window === 'undefined') {
  global.window = global;
}
 
// The ideal input response latency, the time between the input task and the
// first frame of the response.
const BASE_RESPONSE_LATENCY = 16;
 
// we need gl-matrix and jszip for traceviewer
// since it has internal forks for isNode and they get mixed up during
// browserify, we require them locally here and global-ize them.
 
// from catapult/tracing/tracing/base/math.html
const glMatrixModule = require('gl-matrix');
Object.keys(glMatrixModule).forEach(exportName => {
  global[exportName] = glMatrixModule[exportName];
});
// from catapult/tracing/tracing/extras/importer/jszip.html
global.JSZip = {};
global.mannwhitneyu = {};
global.HTMLImportsLoader = {};
global.HTMLImportsLoader.hrefToAbsolutePath = function(path) {
  if (path === '/gl-matrix-min.js') {
    return '../../../lib/empty-stub.js';
  }
  Iif (path === '/jszip.min.js') {
    return '../../../lib/empty-stub.js';
  }
  Eif (path === '/mannwhitneyu.js') {
    return '../../../lib/empty-stub.js';
  }
};
 
require('../../third_party/traceviewer-js/');
const traceviewer = global.tr;
 
class TraceProcessor {
  get RESPONSE() {
    return 'Response';
  }
 
  get ANIMATION() {
    return 'Animation';
  }
 
  get LOAD() {
    return 'Load';
  }
 
  // Create the importer and import the trace contents to a model.
  init(trace) {
    const io = new traceviewer.importer.ImportOptions();
    io.showImportWarnings = false;
    io.pruneEmptyContainers = false;
    io.shiftWorldToZero = true;
 
    const model = new traceviewer.Model();
    const importer = new traceviewer.importer.Import(model, io);
    importer.importTraces([trace]);
 
    return model;
  }
 
  /**
   * Find a main thread from supplied model with matching processId and
   * threadId.
   * @param {!Object} model TraceProcessor Model
   * @param {number} processId
   * @param {number} threadId
   * @return {!Object}
   * @private
   */
  static _findMainThreadFromIds(model, processId, threadId) {
    const modelHelper = model.getOrCreateHelper(traceviewer.model.helpers.ChromeModelHelper);
    const renderHelpers = traceviewer.b.dictionaryValues(modelHelper.rendererHelpers);
    const mainThread = renderHelpers.find(helper => {
      return helper.mainThread &&
        helper.pid === processId &&
        helper.mainThread.tid === threadId;
    }).mainThread;
 
    return mainThread;
  }
 
  /**
   * Calculate duration at specified percentiles for given population of
   * durations.
   * If one of the durations overlaps the end of the window, the full
   * duration should be in the duration array, but the length not included
   * within the window should be given as `clippedLength`. For instance, if a
   * 50ms duration occurs 10ms before the end of the window, `50` should be in
   * the `durations` array, and `clippedLength` should be set to 40.
   * @see https://docs.google.com/document/d/1b9slyaB9yho91YTOkAQfpCdULFkZM9LqsipcX3t7He8/preview
   * @param {!Array<number>} durations Array of durations, sorted in ascending order.
   * @param {number} totalTime Total time (in ms) of interval containing durations.
   * @param {!Array<number>} percentiles Array of percentiles of interest, in ascending order.
   * @param {number=} clippedLength Optional length clipped from a duration overlapping end of window. Default of 0.
   * @return {!Array<{percentile: number, time: number}>}
   * @private
   */
  static _riskPercentiles(durations, totalTime, percentiles, clippedLength = 0) {
    let busyTime = 0;
    for (let i = 0; i < durations.length; i++) {
      busyTime += durations[i];
    }
    busyTime -= clippedLength;
 
    // Start with idle time already complete.
    let completedTime = totalTime - busyTime;
    let duration = 0;
    let cdfTime = completedTime;
    const results = [];
 
    let durationIndex = -1;
    let remainingCount = durations.length + 1;
    if (clippedLength > 0) {
      // If there was a clipped duration, one less in count since one hasn't started yet.
      remainingCount--;
    }
 
    // Find percentiles of interest, in order.
    for (const percentile of percentiles) {
      // Loop over durations, calculating a CDF value for each until it is above
      // the target percentile.
      const percentileTime = percentile * totalTime;
      while (cdfTime < percentileTime && durationIndex < durations.length - 1) {
        completedTime += duration;
        remainingCount -= (duration < 0 ? -1 : 1);
 
        if (clippedLength > 0 && clippedLength < durations[durationIndex + 1]) {
          duration = -clippedLength;
          clippedLength = 0;
        } else {
          durationIndex++;
          duration = durations[durationIndex];
        }
 
        // Calculate value of CDF (multiplied by totalTime) for the end of this duration.
        cdfTime = completedTime + Math.abs(duration) * remainingCount;
      }
 
      // Negative results are within idle time (0ms wait by definition), so clamp at zero.
      results.push({
        percentile,
        time: Math.max(0, (percentileTime - completedTime) / remainingCount) + BASE_RESPONSE_LATENCY
      });
    }
 
    return results;
  }
 
  /**
   * Calculates the maximum queueing time (in ms) of high priority tasks for
   * selected percentiles within a window of the main thread.
   * @see https://docs.google.com/document/d/1b9slyaB9yho91YTOkAQfpCdULFkZM9LqsipcX3t7He8/preview
   * @param {!traceviewer.Model} model
   * @param {{traceEvents: !Array<!Object>}} trace
   * @param {number=} startTime Optional start time (in ms) of range of interest. Defaults to trace start.
   * @param {number=} endTime Optional end time (in ms) of range of interest. Defaults to trace end.
   * @param {!Array<number>=} percentiles Optional array of percentiles to compute. Defaults to [0.5, 0.75, 0.9, 0.99, 1].
   * @return {!Array<{percentile: number, time: number}>}
   */
  static getRiskToResponsiveness(model, trace, startTime, endTime, percentiles) {
    // Range of responsiveness we care about. Default to bounds of model.
    startTime = startTime === undefined ? model.bounds.min : startTime;
    endTime = endTime === undefined ? model.bounds.max : endTime;
    const totalTime = endTime - startTime;
    if (percentiles) {
      percentiles.sort((a, b) => a - b);
    } else {
      percentiles = [0.5, 0.75, 0.9, 0.99, 1];
    }
 
    const ret = TraceProcessor.getMainThreadTopLevelEventDurations(model, trace, startTime,
        endTime);
    return TraceProcessor._riskPercentiles(ret.durations, totalTime, percentiles,
        ret.clippedLength);
  }
 
  /**
   * Provides durations of all main thread top-level events
   * @param {!traceviewer.Model} model
   * @param {{traceEvents: !Array<!Object>}} trace
   * @param {number} startTime Optional start time (in ms) of range of interest. Defaults to trace start.
   * @param {number} endTime Optional end time (in ms) of range of interest. Defaults to trace end.
   * @return {{durations: !Array<number>, clippedLength: number}}
   */
  static getMainThreadTopLevelEventDurations(model, trace, startTime, endTime) {
    // Find the main thread via the first TracingStartedInPage event in the trace
    const startEvent = trace.traceEvents.find(event => {
      return event.name === 'TracingStartedInPage';
    });
    const mainThread = TraceProcessor._findMainThreadFromIds(model, startEvent.pid, startEvent.tid);
 
    // Find durations of all slices in range of interest.
    // TODO(bckenny): filter for top level slices ourselves?
    const durations = [];
    let clippedLength = 0;
    mainThread.sliceGroup.topLevelSlices.forEach(slice => {
      // Discard slices outside range.
 
      if (slice.end <= startTime || slice.start >= endTime) {
        return;
      }
 
      // Clip any at edges of range.
      let duration = slice.duration;
      let sliceStart = slice.start;
      if (sliceStart < startTime) {
        // Any part of task before window can be discarded.
        sliceStart = startTime;
        duration = slice.end - sliceStart;
      }
      if (slice.end > endTime) {
        // Any part of task after window must be clipped but accounted for.
        clippedLength = duration - (endTime - sliceStart);
      }
 
      durations.push(duration);
    });
    durations.sort((a, b) => a - b);
 
    return {
      durations,
      clippedLength
    };
  }
 
  /**
   * Uses traceviewer's statistics package to create a log-normal distribution.
   * Specified by providing the median value, at which the score will be 0.5,
   * and the falloff, the initial point of diminishing returns where any
   * improvement in value will yield increasingly smaller gains in score. Both
   * values should be in the same units (e.g. milliseconds). See
   *   https://www.desmos.com/calculator/tx1wcjk8ch
   * for an interactive view of the relationship between these parameters and
   * the typical parameterization (location and shape) of the log-normal
   * distribution.
   * @param {number} median
   * @param {number} falloff
   * @return {!Statistics.LogNormalDistribution}
   */
  static getLogNormalDistribution(median, falloff) {
    const location = Math.log(median);
 
    // The "falloff" value specified the location of the smaller of the positive
    // roots of the third derivative of the log-normal CDF. Calculate the shape
    // parameter in terms of that value and the median.
    const logRatio = Math.log(falloff / median);
    const shape = 0.5 * Math.sqrt(1 - 3 * logRatio -
        Math.sqrt((logRatio - 3) * (logRatio - 3) - 8));
 
    return new traceviewer.b.Statistics.LogNormalDistribution(location, shape);
  }
}
 
module.exports = TraceProcessor;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/report/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/report/

Statements: 12.28% (14 / 114)      Branches: 0% (0 / 48)      Functions: 0% (0 / 19)      Lines: 12.5% (14 / 112)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/report/
File Statements Branches Functions Lines
handlebar-helpers.js 11.76% (8 / 68) 0% (0 / 32) 0% (0 / 9) 11.94% (8 / 67)
report-generator.js 13.04% (6 / 46) 0% (0 / 16) 0% (0 / 10) 13.33% (6 / 45)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/report/handlebar-helpers.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/report/handlebar-helpers.js

Statements: 11.76% (8 / 68)      Branches: 0% (0 / 32)      Functions: 0% (0 / 9)      Lines: 11.94% (8 / 67)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211                                        1 1   1           1                   1       1             1                                                                                                                                                                                                                                                                                                                           1    
/**
 * @license
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
/* global Intl */
 
const Handlebars = require('handlebars');
const marked = require('marked');
 
const RATINGS = {
  GOOD: {label: 'good', minScore: 75},
  AVERAGE: {label: 'average', minScore: 45},
  POOR: {label: 'poor'}
};
 
function calculateRating(value) {
  let rating = RATINGS.POOR.label;
  if (value >= RATINGS.GOOD.minScore) {
    rating = RATINGS.GOOD.label;
  } else if (value >= RATINGS.AVERAGE.minScore) {
    rating = RATINGS.AVERAGE.label;
  }
  return rating;
}
 
const getTotalScore = function(aggregation) {
  return Math.round(aggregation.total * 100);
};
 
const getItemRating = function(value) {
  if (typeof value === 'boolean') {
    return value ? RATINGS.GOOD.label : RATINGS.POOR.label;
  }
  return calculateRating(value);
};
 
const handlebarHelpers = {
  // Converts a name to a link.
  nameToLink: name => {
    return name.toLowerCase().replace(/\s/g, '-');
  },
 
  // Figures out the total score for an aggregation
  getTotalScore,
 
  // Converts the total score to a rating that can be used for styling.
  getTotalScoreRating: aggregation => {
    const totalScore = getTotalScore(aggregation);
    return calculateRating(totalScore);
  },
 
  // Converts an aggregation's score to a rating that can be used for styling.
  getAggregationScoreRating: score => {
    return calculateRating(Math.round(score * 100));
  },
 
  // Converts a value to a rating string, which can be used inside the report
  // for color styling.
  getItemRating,
 
  // Figures out the icon to display when success or info
  getScoreGoodIcon: informative => informative ? 'info' : 'good',
 
  // Figures out the icon to display when fail or warn
  getScoreBadIcon: (informative, additional) =>
    (informative || additional) ? 'warning score-warning-bg':'poor score-poor-bg',
 
  shouldShowHelpText: value => (getItemRating(value) !== RATINGS.GOOD.label),
 
  // Convert numbers to fixed point decimals
  decimal: number => {
    if (number && number.toFixed) {
      return number.toFixed(2);
    }
    return number;
  },
 
  // value is boolean?
  isBool: value => (typeof value === 'boolean'),
 
  // !value
  not: value => !value,
 
  // value === value2?
  ifEq: function(lhs, rhs, options) {
    if (lhs === rhs) {
      // eslint-disable-next-line no-invalid-this
      return options.fn(this);
    } else {
      // eslint-disable-next-line no-invalid-this
      return options.inverse(this);
    }
  },
 
  // value !== value2
  ifNotEq: function(lhs, rhs, options) {
    if (lhs !== rhs) {
      // eslint-disable-next-line no-invalid-this
      return options.fn(this);
    } else {
      // eslint-disable-next-line no-invalid-this
      return options.inverse(this);
    }
  },
 
  // arg1 && arg2 && ... && argn
  and: (...args) => {
    let arg = false;
    for (let i = 0, n = args.length - 1; i < n; i++) {
      arg = args[i];
      if (!arg) {
        break;
      }
    }
    return arg;
  },
 
  // myFavoriteVar -> my-favorite-var
  kebabCase: str => {
    return (str || '')
      // break up camelCase tokens
      .split(/([A-Z]+[a-z0-9]*)/)
      // replace all special characters and whitespace with hyphens
      .map(part => part.toLowerCase().replace(/[^a-z0-9]+/gi, '-'))
      // rejoin into a single string
      .join('-')
      // de-dupe hyphens
      .replace(/-+/g, '-')
      // remove leading or trailing hyphens
      .replace(/(^-|-$)/g, '');
  },
 
  // eslint-disable-next-line no-unused-vars
  sanitize: (str, opts) => {
    // const isViewer = opts.data.root.reportContext === 'viewer';
 
    // Allow the report to inject HTML, but sanitize it first.
    // Viewer in particular, allows user's to upload JSON. To mitigate against
    // XSS, define a renderer that only transforms a few types of markdown blocks.
    // All other markdown and HTML is ignored.
    const renderer = new marked.Renderer();
    renderer.em = str => `<em>${str}</em>`;
    renderer.link = (href, title, text) => {
      const titleAttr = title ? `title="${title}"` : '';
      return `<a href="${href}" target="_blank" rel="noopener" ${titleAttr}>${text}</a>`;
    };
    renderer.codespan = function(str) {
      return `<code>${str}</code>`;
    };
    // eslint-disable-next-line no-unused-vars
    renderer.code = function(code, language) {
      return `<pre>${Handlebars.Utils.escapeExpression(code)}</pre>`;
    };
    renderer.image = function(src, title, text) {
      return `<img src="${src}" alt="${text}" title="${title}">`;
    };
 
    // Nuke wrapper <p> tag that gets generated.
    renderer.paragraph = function(str) {
      return str;
    };
 
    try {
      str = marked(str, {renderer, sanitize: true});
    } catch (e) {
      // Ignore fatal errors from marked js.
    }
 
    // The input str has been sanitized and transformed. Mark it as safe so
    // handlebars renders the text as HTML.
    return new Handlebars.SafeString(str);
  },
 
  // format time
  formatDateTime: date => {
    const options = {
      day: 'numeric', month: 'numeric', year: 'numeric',
      hour: 'numeric', minute: 'numeric', second: 'numeric',
      timeZoneName: 'short'
    };
    let formatter = new Intl.DateTimeFormat('en-US', options);
 
    // Force UTC if runtime timezone could not be detected.
    // See https://github.com/GoogleChrome/lighthouse/issues/1056
    const tz = formatter.resolvedOptions().timeZone;
    if (!tz || tz.toLowerCase() === 'etc/unknown') {
      options.timeZone = 'UTC';
      formatter = new Intl.DateTimeFormat('en-US', options);
    }
    return formatter.format(new Date(date));
  }
 
};
 
module.exports = handlebarHelpers;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/report/report-generator.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/report/report-generator.js

Statements: 13.04% (6 / 46)      Branches: 0% (0 / 16)      Functions: 0% (0 / 10)      Lines: 13.33% (6 / 45)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208                                        1 1 1 1 1                                                                                                                                                                                                                                                                                                                                                                         1    
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
/* global Intl */
 
const Formatter = require('../formatters/formatter');
const Handlebars = require('handlebars');
const handlebarHelpers = require('./handlebar-helpers');
const fs = require('fs');
const path = require('path');
 
 
class ReportGenerator {
 
  constructor() {
    Handlebars.registerHelper(handlebarHelpers);
  }
 
  /**
   * Escape closing script tags.
   * @param {string} jsonStr
   * @return {string}
   */
  _escapeScriptTags(jsonStr) {
    return jsonStr.replace(/<\/script>/g, '<\\/script>');
  }
 
  /**
   * Gets the template for the report.
   * @return {string}
   */
  getReportTemplate() {
    return fs.readFileSync(path.join(__dirname, './templates/report-template.html'), 'utf8');
  }
 
  /**
   * Gets the template for any exceptions.
   * @return {string}
   */
  getExceptionTemplate() {
    return fs.readFileSync(path.join(__dirname, './templates/exception.html'), 'utf8');
  }
 
  /**
   * Gets the CSS for the report.
   * @return {!Array<string>} an array of CSS
   */
  getReportCSS() {
    // Cannot DRY this up and dynamically create paths because fs.readdirSync
    // doesn't browserify well with a variable path. See https://github.com/substack/brfs/issues/36.
    const partialStyles = [
      fs.readFileSync(__dirname + '/../formatters/partials/cards.css', 'utf8'),
      fs.readFileSync(__dirname + '/../formatters/partials/critical-request-chains.css', 'utf8'),
      fs.readFileSync(__dirname + '/../formatters/partials/table.css', 'utf8'),
      fs.readFileSync(__dirname + '/../formatters/partials/url-list.css', 'utf8'),
      fs.readFileSync(__dirname + '/../formatters/partials/user-timings.css', 'utf8')
    ];
 
    return [
      fs.readFileSync(path.join(__dirname, './styles/report.css'), 'utf8'),
      ...partialStyles
    ];
  }
 
  /**
   * Gets the script for the report UI
   * @param {string} reportContext
   * @return {!Array<string>} an array of scripts
   */
  getReportJS(reportContext) {
    if (reportContext === 'devtools') {
      return [];
    } else {
      return [
        fs.readFileSync(path.join(__dirname, './scripts/logger.js'), 'utf8'),
        fs.readFileSync(path.join(__dirname, '../lib/file-namer.js'), 'utf8'),
        fs.readFileSync(path.join(__dirname, './scripts/lighthouse-report.js'), 'utf8')
      ];
    }
  }
 
  /**
   * Refactors the PWA audits into their respective tech categories, i.e. offline, manifest, etc
   * because the report itself supports viewing them by user feature (default), or by category.
   */
  _createPWAAuditsByCategory(aggregations) {
    const items = {};
 
    aggregations.forEach(aggregation => {
      // We only regroup the PWA aggregations so ignore any
      // that don't match that name, i.e. Best Practices, metrics.
      if (!aggregation.categorizable) {
        return;
      }
 
      aggregation.score.forEach(score => {
        score.subItems.forEach(subItem => {
          // Create a space for the category.
          if (!items[subItem.category]) {
            items[subItem.category] = {};
          }
 
          // Then use the name to de-dupe the same audit from different aggregations.
          if (!items[subItem.category][subItem.name]) {
            items[subItem.category][subItem.name] = subItem;
          }
        });
      });
    });
 
    return items;
  }
 
  /**
   * Creates the page describing any error generated while running generateHTML()
   * @param {!Error} err Exception thrown from generateHTML.
   * @param {!Object} results Lighthouse results.
   * @return {string} HTML of the exception page.
   */
  renderException(err, results) {
    const template = Handlebars.compile(this.getExceptionTemplate());
    return template({
      errMessage: err.message,
      errStack: err.stack,
      css: this.getReportCSS(),
      results: JSON.stringify(results, null, 2)
    });
  }
 
  /**
   * Register the formatter for each extendedInfo.
   * @param {!Object} audits Lighthouse results.audits.
   */
  _registerFormatters(audits) {
    Object.keys(audits).forEach(audit => {
      // Use value rather than key for audit.
      audit = audits[audit];
 
      if (!audit.extendedInfo) {
        return;
      }
      if (!audit.extendedInfo.formatter) {
        // HTML formatter not provided for this subItem
        return;
      }
      const formatter = Formatter.getByName(audit.extendedInfo.formatter);
      const helpers = formatter.getHelpers();
      if (helpers) {
        Handlebars.registerHelper(helpers);
      }
 
      Handlebars.registerPartial(audit.name, formatter.getFormatter('html'));
    });
  }
 
  /**
   * Generates the Lighthouse report HTML.
   * @param {!Object} results Lighthouse results.
   * @param {!string} reportContext What app is requesting the report (eg. devtools, extension)
   * @param {?Object} reportsCatalog Basic info about all the reports to include in left nav bar
   * @return {string} HTML of the report page.
   */
  generateHTML(results, reportContext = 'extension', reportsCatalog) {
    this._registerFormatters(results.audits);
 
    results.aggregations.forEach(aggregation => {
      aggregation.score.forEach(score => {
        // Map subItem strings to auditResults from results.audits.
        // Coming soon events are not in auditResults, but rather still in subItems.
        score.subItems = score.subItems.map(subItem => results.audits[subItem] || subItem);
      });
    });
 
    const template = Handlebars.compile(this.getReportTemplate());
    return template({
      url: results.url,
      lighthouseVersion: results.lighthouseVersion,
      generatedTime: results.generatedTime,
      lhresults: this._escapeScriptTags(JSON.stringify(results, null, 2)),
      stylesheets: this.getReportCSS(),
      reportContext: reportContext,
      scripts: this.getReportJS(reportContext),
      aggregations: results.aggregations,
      auditsByCategory: this._createPWAAuditsByCategory(results.aggregations),
      runtimeConfig: results.runtimeConfig,
      reportsCatalog
    });
  }
}
 
module.exports = ReportGenerator;
 
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/

Statements: 100% (4 / 4)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/
File Statements Branches Functions Lines
index.js 100% (4 / 4) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/index.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/index.js

Statements: 100% (4 / 4)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./importer/import.js");require("./model/model.js");require("./extras/lean_config.js");require("./metrics/all_metrics.js");
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/

Statements: 30.01% (858 / 2859)      Branches: 11.73% (125 / 1066)      Functions: 21.58% (112 / 519)      Lines: 100% (32 / 32)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/
File Statements Branches Functions Lines
base.js 33.67% (33 / 98) 37.5% (12 / 32) 33.33% (4 / 12) 100% (1 / 1)
base64.js 23.4% (11 / 47) 0% (0 / 24) 12.5% (1 / 8) 100% (1 / 1)
category_util.js 50% (6 / 12) 0% (0 / 2) 50% (1 / 2) 100% (1 / 1)
color.js 69.92% (86 / 123) 66.07% (37 / 56) 52.17% (12 / 23) 100% (1 / 1)
color_scheme.js 84.29% (59 / 70) 25% (1 / 4) 76.47% (13 / 17) 100% (1 / 1)
event.js 55.17% (16 / 29) 37.5% (3 / 8) 28.57% (2 / 7) 100% (1 / 1)
event_target.js 47.69% (31 / 65) 37.5% (12 / 32) 30.77% (4 / 13) 100% (1 / 1)
extension_registry.js 89.47% (17 / 19) 62.5% (5 / 8) 100% (2 / 2) 100% (1 / 1)
extension_registry_base.js 79.59% (39 / 49) 50% (10 / 20) 81.82% (9 / 11) 100% (1 / 1)
extension_registry_basic.js 50.7% (36 / 71) 22.22% (4 / 18) 33.33% (4 / 12) 100% (1 / 1)
extension_registry_type_based.js 48.35% (44 / 91) 41.18% (14 / 34) 50% (7 / 14) 100% (1 / 1)
guid.js 57.14% (8 / 14) 0% (0 / 2) 40% (2 / 5) 100% (1 / 1)
interval_tree.js 7.69% (10 / 130) 0% (0 / 60) 2.38% (1 / 42) 100% (1 / 1)
iteration_helpers.js 21.74% (45 / 207) 2.5% (2 / 80) 13.79% (4 / 29) 100% (1 / 1)
math.js 40% (34 / 85) 8.33% (1 / 12) 15.79% (3 / 19) 100% (1 / 1)
multi_dimensional_view.js 6.91% (17 / 246) 0% (0 / 67) 3.85% (1 / 26) 100% (1 / 1)
piecewise_linear_function.js 14.52% (9 / 62) 0% (0 / 24) 6.67% (1 / 15) 100% (1 / 1)
quad.js 22.83% (29 / 127) 0% (0 / 14) 5.26% (1 / 19) 100% (1 / 1)
raf.js 25.47% (27 / 106) 0% (0 / 52) 5% (1 / 20) 100% (1 / 1)
range.js 26.52% (35 / 132) 3.75% (3 / 80) 20% (7 / 35) 100% (1 / 1)
range_utils.js 14.49% (10 / 69) 0% (0 / 32) 10% (1 / 10) 100% (1 / 1)
rect.js 11.54% (9 / 78) 0% (0 / 7) 4.55% (1 / 22) 100% (1 / 1)
running_statistics.js 6.86% (7 / 102) 0% (0 / 48) 11.76% (2 / 17) 100% (1 / 1)
sinebow_color_generator.js 93.48% (43 / 46) 50% (4 / 8) 100% (7 / 7) 100% (1 / 1)
sorted_array_utils.js 10% (12 / 120) 0% (0 / 98) 10% (1 / 10) 100% (1 / 1)
statistics.js 17.35% (51 / 294) 4.26% (4 / 94) 8.33% (5 / 60) 100% (1 / 1)
task.js 15.28% (11 / 72) 0% (0 / 22) 6.67% (1 / 15) 100% (1 / 1)
time_display_modes.js 77.78% (7 / 9) 100% (0 / 0) 33.33% (1 / 3) 100% (1 / 1)
timing.js 28% (14 / 50) 0% (0 / 12) 8.33% (1 / 12) 100% (1 / 1)
unit.js 48.03% (73 / 152) 14.29% (10 / 70) 40% (8 / 20) 100% (1 / 1)
unit_scale.js 85.71% (18 / 21) 50% (3 / 6) 100% (3 / 3) 100% (1 / 1)
utils.js 17.46% (11 / 63) 0% (0 / 40) 11.11% (1 / 9) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/base.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/base.js

Statements: 33.67% (33 / 98)      Branches: 37.5% (12 / 32)      Functions: 33.33% (4 / 12)      Lines: 100% (1 / 1)      Ignored: none     

1 2377  
"use strict";'use strict';global.tr=function(){Iif(global.tr){console.warn('Base was multiply initialized. First init wins.');return global.tr;}function exportPath(name){var parts=name.split('.');var cur=global;for(var part;parts.length&&(part=parts.shift());){if(part in cur){cur=cur[part];}else{cur=cur[part]={};}}return cur;};function isExported(name){var parts=name.split('.');var cur=global;for(var part;parts.length&&(part=parts.shift());){if(part in cur){cur=cur[part];}else{return false;}}return true;}function isDefined(name){var parts=name.split('.');var curObject=global;for(var i=0;i<parts.length;i++){var partName=parts[i];var nextObject=curObject[partName];if(nextObject===undefined)return false;curObject=nextObject;}return true;}var panicElement=undefined;var rawPanicMessages=[];function showPanicElementIfNeeded(){if(panicElement)return;var panicOverlay=document.createElement('div');panicOverlay.style.backgroundColor='white';panicOverlay.style.border='3px solid red';panicOverlay.style.boxSizing='border-box';panicOverlay.style.color='black';panicOverlay.style.display='-webkit-flex';panicOverlay.style.height='100%';panicOverlay.style.left=0;panicOverlay.style.padding='8px';panicOverlay.style.position='fixed';panicOverlay.style.top=0;panicOverlay.style.webkitFlexDirection='column';panicOverlay.style.width='100%';panicElement=document.createElement('div');panicElement.style.webkitFlex='1 1 auto';panicElement.style.overflow='auto';panicOverlay.appendChild(panicElement);if(!document.body){setTimeout(function(){document.body.appendChild(panicOverlay);},150);}else{document.body.appendChild(panicOverlay);}}function showPanic(panicTitle,panicDetails){if(tr.isHeadless){if(panicDetails instanceof Error)throw panicDetails;throw new Error('Panic: '+panicTitle+':\n'+panicDetails);}if(panicDetails instanceof Error)panicDetails=panicDetails.stack;showPanicElementIfNeeded();var panicMessageEl=document.createElement('div');panicMessageEl.innerHTML='<h2 id="message"></h2>'+'<pre id="details"></pre>';panicMessageEl.querySelector('#message').textContent=panicTitle;panicMessageEl.querySelector('#details').textContent=panicDetails;panicElement.appendChild(panicMessageEl);rawPanicMessages.push({title:panicTitle,details:panicDetails});}function hasPanic(){return rawPanicMessages.length!==0;}function getPanicText(){return rawPanicMessages.map(function(msg){return msg.title;}).join(', ');}function exportTo(namespace,fn){var obj=exportPath(namespace);var exports=fn();for(var propertyName in exports){var propertyDescriptor=Object.getOwnPropertyDescriptor(exports,propertyName);Eif(propertyDescriptor)Object.defineProperty(obj,propertyName,propertyDescriptor);}};function initialize(){Iif(global.isVinn){tr.isVinn=true;}else Eif(global.process&&global.process.versions.node){tr.isNode=true;}else{tr.isVinn=false;tr.isNode=false;tr.doc=document;tr.isMac=/Mac/.test(navigator.platform);tr.isWindows=/Win/.test(navigator.platform);tr.isChromeOS=/CrOS/.test(navigator.userAgent);tr.isLinux=/Linux/.test(navigator.userAgent);}tr.isHeadless=tr.isVinn||tr.isNode;}return{initialize:initialize,exportTo:exportTo,isExported:isExported,isDefined:isDefined,showPanic:showPanic,hasPanic:hasPanic,getPanicText:getPanicText};}();tr.initialize();
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/base64.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/base64.js

Statements: 23.4% (11 / 47)      Branches: 0% (0 / 24)      Functions: 12.5% (1 / 8)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function Base64(){}function b64ToUint6(nChr){if(nChr>64&&nChr<91)return nChr-65;if(nChr>96&&nChr<123)return nChr-71;if(nChr>47&&nChr<58)return nChr+4;if(nChr===43)return 62;if(nChr===47)return 63;return 0;}Base64.getDecodedBufferLength=function(input){return input.length*3+1>>2;};Base64.EncodeArrayBufferToString=function(input){var binary='';var bytes=new Uint8Array(input);var len=bytes.byteLength;for(var i=0;i<len;i++)binary+=String.fromCharCode(bytes[i]);return btoa(binary);};Base64.DecodeToTypedArray=function(input,output){var nInLen=input.length;var nOutLen=nInLen*3+1>>2;var nMod3=0;var nMod4=0;var nUint24=0;var nOutIdx=0;if(nOutLen>output.byteLength)throw new Error('Output buffer too small to decode.');for(var nInIdx=0;nInIdx<nInLen;nInIdx++){nMod4=nInIdx&3;nUint24|=b64ToUint6(input.charCodeAt(nInIdx))<<18-6*nMod4;if(nMod4===3||nInLen-nInIdx===1){for(nMod3=0;nMod3<3&&nOutIdx<nOutLen;nMod3++,nOutIdx++){output.setUint8(nOutIdx,nUint24>>>(16>>>nMod3&24)&255);}nUint24=0;}}return nOutIdx-1;};Base64.btoa=function(input){return btoa(input);};Base64.atob=function(input){return atob(input);};return{Base64:Base64};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/category_util.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/category_util.js

Statements: 50% (6 / 12)      Branches: 0% (0 / 2)      Functions: 50% (1 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){var categoryPartsFor={};function getCategoryParts(category){var parts=categoryPartsFor[category];if(parts!==undefined)return parts;parts=category.split(',');categoryPartsFor[category]=parts;return parts;}return{getCategoryParts:getCategoryParts};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/color.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/color.js

Statements: 69.92% (86 / 123)      Branches: 66.07% (37 / 56)      Functions: 52.17% (12 / 23)      Lines: 100% (1 / 1)      Ignored: none     

1 2840  
"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function clamp01(value){return Math.max(0,Math.min(1,value));}function Color(opt_r,opt_g,opt_b,opt_a){this.r=Math.floor(opt_r)||0;this.g=Math.floor(opt_g)||0;this.b=Math.floor(opt_b)||0;this.a=opt_a;}Color.fromString=function(str){var tmp;var values;Iif(str.substr(0,4)=='rgb('){tmp=str.substr(4,str.length-5);values=tmp.split(',').map(function(v){return v.replace(/^\s+/,'','g');});if(values.length!=3)throw new Error('Malformatted rgb-expression');return new Color(parseInt(values[0]),parseInt(values[1]),parseInt(values[2]));}else Eif(str.substr(0,5)=='rgba('){tmp=str.substr(5,str.length-6);values=tmp.split(',').map(function(v){return v.replace(/^\s+/,'','g');});Iif(values.length!=4)throw new Error('Malformatted rgb-expression');return new Color(parseInt(values[0]),parseInt(values[1]),parseInt(values[2]),parseFloat(values[3]));}else if(str[0]=='#'&&str.length==7){return new Color(parseInt(str.substr(1,2),16),parseInt(str.substr(3,2),16),parseInt(str.substr(5,2),16));}else{throw new Error('Unrecognized string format.');}};Color.lerp=function(a,b,percent){if(a.a!==undefined&&b.a!==undefined)return Color.lerpRGBA(a,b,percent);return Color.lerpRGB(a,b,percent);};Color.lerpRGB=function(a,b,percent){return new Color((b.r-a.r)*percent+a.r,(b.g-a.g)*percent+a.g,(b.b-a.b)*percent+a.b);};Color.lerpRGBA=function(a,b,percent){return new Color((b.r-a.r)*percent+a.r,(b.g-a.g)*percent+a.g,(b.b-a.b)*percent+a.b,(b.a-a.a)*percent+a.a);};Color.fromDict=function(dict){return new Color(dict.r,dict.g,dict.b,dict.a);};Color.fromHSLExplicit=function(h,s,l,a){var r,g,b;function hue2rgb(p,q,t){if(t<0)t+=1;if(t>1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*(2/3-t)*6;return p;}if(s===0){r=g=b=l;}else{var q=l<0.5?l*(1+s):l+s-l*s;var p=2*l-q;r=hue2rgb(p,q,h+1/3);g=hue2rgb(p,q,h);b=hue2rgb(p,q,h-1/3);}return new Color(Math.floor(r*255),Math.floor(g*255),Math.floor(b*255),a);};Color.fromHSL=function(hsl){return Color.fromHSLExplicit(hsl.h,hsl.s,hsl.l,hsl.a);};Color.prototype={clone:function(){var c=new Color();c.r=this.r;c.g=this.g;c.b=this.b;c.a=this.a;return c;},blendOver:function(bgColor){var oneMinusThisAlpha=1-this.a;var outA=this.a+bgColor.a*oneMinusThisAlpha;var bgBlend=bgColor.a*oneMinusThisAlpha/bgColor.a;return new Color(this.r*this.a+bgColor.r*bgBlend,this.g*this.a+bgColor.g*bgBlend,this.b*this.a+bgColor.b*bgBlend,outA);},brighten:function(opt_k){var k;k=opt_k||0.45;return new Color(Math.min(255,this.r+Math.floor(this.r*k)),Math.min(255,this.g+Math.floor(this.g*k)),Math.min(255,this.b+Math.floor(this.b*k)),this.a);},lighten:function(k,opt_maxL){var maxL=opt_maxL!==undefined?opt_maxL:1.0;var hsl=this.toHSL();hsl.l=clamp01(hsl.l+k);return Color.fromHSL(hsl);},darken:function(opt_k){var k;if(opt_k!==undefined)k=opt_k;else k=0.45;return new Color(Math.min(255,this.r-Math.floor(this.r*k)),Math.min(255,this.g-Math.floor(this.g*k)),Math.min(255,this.b-Math.floor(this.b*k)),this.a);},desaturate:function(opt_desaturateFactor){var desaturateFactor;if(opt_desaturateFactor!==undefined)desaturateFactor=opt_desaturateFactor;else desaturateFactor=1;var hsl=this.toHSL();hsl.s=clamp01(hsl.s*(1-desaturateFactor));return Color.fromHSL(hsl);},withAlpha:function(a){return new Color(this.r,this.g,this.b,a);},toString:function(){Iif(this.a!==undefined){return'rgba('+this.r+','+this.g+','+this.b+','+this.a+')';}return'rgb('+this.r+','+this.g+','+this.b+')';},toHSL:function(){var r=this.r/255;var g=this.g/255;var b=this.b/255;var max=Math.max(r,g,b);var min=Math.min(r,g,b);var h,s;var l=(max+min)/2;if(min===max){h=0;s=0;}else{var delta=max-min;if(l>0.5)s=delta/(2-max-min);else s=delta/(max+min);if(r===max){h=(g-b)/delta;if(g<b)h+=6;}else if(g===max){h=2+(b-r)/delta;}else{h=4+(r-g)/delta;}h/=6;}return{h:h,s:s,l:l,a:this.a};},toStringWithAlphaOverride:function(alpha){return'rgba('+this.r+','+this.g+','+this.b+','+alpha+')';}};return{Color:Color};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/color_scheme.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/color_scheme.js

Statements: 84.29% (59 / 70)      Branches: 25% (1 / 4)      Functions: 76.47% (13 / 17)      Lines: 100% (1 / 1)      Ignored: none     

1 2434  
"use strict";require("./base.js");require("./color.js");require("./iteration_helpers.js");'use strict';global.tr.exportTo('tr.b',function(){var generalPurposeColors=[new tr.b.Color(122,98,135),new tr.b.Color(150,83,105),new tr.b.Color(44,56,189),new tr.b.Color(99,86,147),new tr.b.Color(104,129,107),new tr.b.Color(130,178,55),new tr.b.Color(87,109,147),new tr.b.Color(111,145,88),new tr.b.Color(81,152,131),new tr.b.Color(142,91,111),new tr.b.Color(81,163,70),new tr.b.Color(148,94,86),new tr.b.Color(144,89,118),new tr.b.Color(83,150,97),new tr.b.Color(105,94,139),new tr.b.Color(89,144,122),new tr.b.Color(105,119,128),new tr.b.Color(96,128,137),new tr.b.Color(145,88,145),new tr.b.Color(88,145,144),new tr.b.Color(90,100,143),new tr.b.Color(121,97,136),new tr.b.Color(111,160,73),new tr.b.Color(112,91,142),new tr.b.Color(86,147,86),new tr.b.Color(63,100,170),new tr.b.Color(81,152,107),new tr.b.Color(60,164,173),new tr.b.Color(143,72,161),new tr.b.Color(159,74,86)];var reservedColorsByName={thread_state_uninterruptible:new tr.b.Color(182,125,143),thread_state_iowait:new tr.b.Color(255,140,0),thread_state_running:new tr.b.Color(126,200,148),thread_state_runnable:new tr.b.Color(133,160,210),thread_state_sleeping:new tr.b.Color(240,240,240),thread_state_unknown:new tr.b.Color(199,155,125),background_memory_dump:new tr.b.Color(0,180,180),light_memory_dump:new tr.b.Color(0,0,180),detailed_memory_dump:new tr.b.Color(180,0,180),generic_work:new tr.b.Color(125,125,125),good:new tr.b.Color(0,125,0),bad:new tr.b.Color(180,125,0),terrible:new tr.b.Color(180,0,0),black:new tr.b.Color(0,0,0),rail_response:new tr.b.Color(67,135,253),rail_animation:new tr.b.Color(244,74,63),rail_idle:new tr.b.Color(238,142,0),rail_load:new tr.b.Color(13,168,97),startup:new tr.b.Color(230,230,0),used_memory_column:new tr.b.Color(0,0,255),older_used_memory_column:new tr.b.Color(153,204,255),tracing_memory_column:new tr.b.Color(153,153,153),heap_dump_stack_frame:new tr.b.Color(128,128,128),heap_dump_object_type:new tr.b.Color(0,0,255),heap_dump_child_node_arrow:new tr.b.Color(204,102,0),cq_build_running:new tr.b.Color(255,255,119),cq_build_passed:new tr.b.Color(153,238,102),cq_build_failed:new tr.b.Color(238,136,136),cq_build_abandoned:new tr.b.Color(187,187,187),cq_build_attempt_runnig:new tr.b.Color(222,222,75),cq_build_attempt_passed:new tr.b.Color(103,218,35),cq_build_attempt_failed:new tr.b.Color(197,81,81)};var numGeneralPurposeColorIds=generalPurposeColors.length;var numReservedColorIds=tr.b.dictionaryLength(reservedColorsByName);var numColorsPerVariant=numGeneralPurposeColorIds+numReservedColorIds;function ColorScheme(){}var paletteBase=[];paletteBase.push.apply(paletteBase,generalPurposeColors);paletteBase.push.apply(paletteBase,tr.b.dictionaryValues(reservedColorsByName));ColorScheme.colors=[];ColorScheme.properties={};ColorScheme.properties={numColorsPerVariant:numColorsPerVariant};function pushVariant(func){var variantColors=paletteBase.map(func);ColorScheme.colors.push.apply(ColorScheme.colors,variantColors);}pushVariant(function(c){return c;});ColorScheme.properties.brightenedOffsets=[];ColorScheme.properties.brightenedOffsets.push(ColorScheme.colors.length);pushVariant(function(c){return c.lighten(0.3,0.9);});ColorScheme.properties.brightenedOffsets.push(ColorScheme.colors.length);pushVariant(function(c){return c.lighten(0.48,0.9);});ColorScheme.properties.brightenedOffsets.push(ColorScheme.colors.length);pushVariant(function(c){return c.lighten(0.65,0.9);});ColorScheme.properties.dimmedOffsets=[];ColorScheme.properties.dimmedOffsets.push(ColorScheme.colors.length);pushVariant(function(c){return c.desaturate();});ColorScheme.properties.dimmedOffsets.push(ColorScheme.colors.length);pushVariant(function(c){return c.desaturate(0.5);});ColorScheme.properties.dimmedOffsets.push(ColorScheme.colors.length);pushVariant(function(c){return c.desaturate(0.3);});ColorScheme.colorsAsStrings=ColorScheme.colors.map(function(c){return c.toString();});var reservedColorNameToIdMap=function(){var m=new Map();var i=generalPurposeColors.length;tr.b.iterItems(reservedColorsByName,function(key,value){m.set(key,i++);});return m;}();ColorScheme.getColorIdForReservedName=function(name){var id=reservedColorNameToIdMap.get(name);Iif(id===undefined)throw new Error('Unrecognized color ')+name;return id;};ColorScheme.getColorForReservedNameAsString=function(reservedName){var id=ColorScheme.getColorIdForReservedName(reservedName);return ColorScheme.colorsAsStrings[id];};ColorScheme.getStringHash=function(name){var hash=0;for(var i=0;i<name.length;++i)hash=(hash+37*hash+11*name.charCodeAt(i))%0xFFFFFFFF;return hash;};var stringColorIdCache=new Map();ColorScheme.getColorIdForGeneralPurposeString=function(string){if(stringColorIdCache.get(string)===undefined){var hash=ColorScheme.getStringHash(string);stringColorIdCache.set(string,hash%numGeneralPurposeColorIds);}return stringColorIdCache.get(string);};return{ColorScheme:ColorScheme};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/event.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/event.js

Statements: 55.17% (16 / 29)      Branches: 37.5% (3 / 8)      Functions: 28.57% (2 / 7)      Lines: 100% (1 / 1)      Ignored: none     

1 2105  
"use strict";require("./event_target.js");'use strict';global.tr.exportTo('tr.b',function(){var Event;Eif(tr.isHeadless){function HeadlessEvent(type,opt_bubbles,opt_preventable){this.type=type;this.bubbles=opt_bubbles!==undefined?!!opt_bubbles:false;this.cancelable=opt_preventable!==undefined?!!opt_preventable:false;this.defaultPrevented=false;this.cancelBubble=false;};HeadlessEvent.prototype={preventDefault:function(){this.defaultPrevented=true;},stopPropagation:function(){this.cancelBubble=true;}};Event=HeadlessEvent;}else{function TrEvent(type,opt_bubbles,opt_preventable){var e=tr.doc.createEvent('Event');e.initEvent(type,!!opt_bubbles,!!opt_preventable);e.__proto__=global.Event.prototype;return e;};TrEvent.prototype={__proto__:global.Event.prototype};Event=TrEvent;}function dispatchSimpleEvent(target,type,opt_bubbles,opt_cancelable,opt_fields){var e=new tr.b.Event(type,opt_bubbles,opt_cancelable);if(opt_fields){tr.b.iterItems(opt_fields,function(name,value){e[name]=value;});}return target.dispatchEvent(e);}return{Event:Event,dispatchSimpleEvent:dispatchSimpleEvent};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/event_target.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/event_target.js

Statements: 47.69% (31 / 65)      Branches: 37.5% (12 / 32)      Functions: 30.77% (4 / 13)      Lines: 100% (1 / 1)      Ignored: none     

1 2105  
"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function EventTarget(){}EventTarget.decorate=function(target){for(var k in EventTarget.prototype){Iif(k=='decorate')continue;var v=EventTarget.prototype[k];Iif(typeof v!=='function')continue;target[k]=v;}};EventTarget.prototype={addEventListener:function(type,handler){if(!this.listeners_)this.listeners_=Object.create(null);Eif(!(type in this.listeners_)){this.listeners_[type]=[handler];}else{var handlers=this.listeners_[type];if(handlers.indexOf(handler)<0)handlers.push(handler);}},removeEventListener:function(type,handler){if(!this.listeners_)return;if(type in this.listeners_){var handlers=this.listeners_[type];var index=handlers.indexOf(handler);if(index>=0){if(handlers.length==1)delete this.listeners_[type];else handlers.splice(index,1);}}},dispatchEvent:function(event){if(!this.listeners_)return true;var self=this;event.__defineGetter__('target',function(){return self;});var realPreventDefault=event.preventDefault;event.preventDefault=function(){realPreventDefault.call(this);this.rawReturnValue=false;};var type=event.type;var prevented=0;if(type in this.listeners_){var handlers=this.listeners_[type].concat();for(var i=0,handler;handler=handlers[i];i++){Iif(handler.handleEvent)prevented|=handler.handleEvent.call(handler,event)===false;else prevented|=handler.call(this,event)===false;}}return!prevented&&event.rawReturnValue;},hasEventListener:function(type){return this.listeners_[type]!==undefined;}};var EventTargetHelper={decorate:function(target){for(var k in EventTargetHelper){if(k=='decorate')continue;var v=EventTargetHelper[k];if(typeof v!=='function')continue;target[k]=v;}target.listenerCounts_={};},addEventListener:function(type,listener,useCapture){this.__proto__.addEventListener.call(this,type,listener,useCapture);if(this.listenerCounts_[type]===undefined)this.listenerCounts_[type]=0;this.listenerCounts_[type]++;},removeEventListener:function(type,listener,useCapture){this.__proto__.removeEventListener.call(this,type,listener,useCapture);this.listenerCounts_[type]--;},hasEventListener:function(type){return this.listenerCounts_[type]>0;}};return{EventTarget:EventTarget,EventTargetHelper:EventTargetHelper};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/extension_registry.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/extension_registry.js

Statements: 89.47% (17 / 19)      Branches: 62.5% (5 / 8)      Functions: 100% (2 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 222  
"use strict";require("./event_target.js");require("./extension_registry_base.js");require("./extension_registry_basic.js");require("./extension_registry_type_based.js");require("./iteration_helpers.js");'use strict';global.tr.exportTo('tr.b',function(){function decorateExtensionRegistry(registry,registryOptions){Iif(registry.register)throw new Error('Already has registry');registryOptions.freeze();if(registryOptions.mode==tr.b.BASIC_REGISTRY_MODE){tr.b._decorateBasicExtensionRegistry(registry,registryOptions);}else Eif(registryOptions.mode==tr.b.TYPE_BASED_REGISTRY_MODE){tr.b._decorateTypeBasedExtensionRegistry(registry,registryOptions);}else{throw new Error('Unrecognized mode');}Eif(registry.addEventListener===undefined)tr.b.EventTarget.decorate(registry);}return{decorateExtensionRegistry:decorateExtensionRegistry};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/extension_registry_base.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/extension_registry_base.js

Statements: 79.59% (39 / 49)      Branches: 50% (10 / 20)      Functions: 81.82% (9 / 11)      Lines: 100% (1 / 1)      Ignored: none     

1 252  
"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function RegisteredTypeInfo(constructor,metadata){this.constructor=constructor;this.metadata=metadata;};var BASIC_REGISTRY_MODE='BASIC_REGISTRY_MODE';var TYPE_BASED_REGISTRY_MODE='TYPE_BASED_REGISTRY_MODE';var ALL_MODES={BASIC_REGISTRY_MODE:true,TYPE_BASED_REGISTRY_MODE:true};function ExtensionRegistryOptions(mode){Iif(mode===undefined)throw new Error('Mode is required');Iif(!ALL_MODES[mode])throw new Error('Not a mode.');this.mode_=mode;this.defaultMetadata_={};this.defaultConstructor_=undefined;this.defaultTypeInfo_=undefined;this.frozen_=false;}ExtensionRegistryOptions.prototype={freeze:function(){Iif(this.frozen_)throw new Error('Frozen');this.frozen_=true;},get mode(){return this.mode_;},get defaultMetadata(){return this.defaultMetadata_;},set defaultMetadata(defaultMetadata){Iif(this.frozen_)throw new Error('Frozen');this.defaultMetadata_=defaultMetadata;this.defaultTypeInfo_=undefined;},get defaultConstructor(){return this.defaultConstructor_;},set defaultConstructor(defaultConstructor){Iif(this.frozen_)throw new Error('Frozen');this.defaultConstructor_=defaultConstructor;this.defaultTypeInfo_=undefined;},get defaultTypeInfo(){if(this.defaultTypeInfo_===undefined&&this.defaultConstructor_){this.defaultTypeInfo_=new RegisteredTypeInfo(this.defaultConstructor,this.defaultMetadata);}return this.defaultTypeInfo_;},validateConstructor:function(constructor){if(!this.mandatoryBaseClass)return;var curProto=constructor.prototype.__proto__;var ok=false;while(curProto){if(curProto===this.mandatoryBaseClass.prototype){ok=true;break;}curProto=curProto.__proto__;}Iif(!ok)throw new Error(constructor+'must be subclass of '+registry);}};return{BASIC_REGISTRY_MODE:BASIC_REGISTRY_MODE,TYPE_BASED_REGISTRY_MODE:TYPE_BASED_REGISTRY_MODE,ExtensionRegistryOptions:ExtensionRegistryOptions,RegisteredTypeInfo:RegisteredTypeInfo};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/extension_registry_basic.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/extension_registry_basic.js

Statements: 50.7% (36 / 71)      Branches: 22.22% (4 / 18)      Functions: 33.33% (4 / 12)      Lines: 100% (1 / 1)      Ignored: none     

1 2298  
"use strict";require("./event.js");require("./extension_registry_base.js");'use strict';global.tr.exportTo('tr.b',function(){var RegisteredTypeInfo=tr.b.RegisteredTypeInfo;var ExtensionRegistryOptions=tr.b.ExtensionRegistryOptions;function decorateBasicExtensionRegistry(registry,extensionRegistryOptions){var savedStateStack=[];registry.registeredTypeInfos_=[];registry.register=function(constructor,opt_metadata){Iif(registry.findIndexOfRegisteredConstructor(constructor)!==undefined)throw new Error('Handler already registered for '+constructor);extensionRegistryOptions.validateConstructor(constructor);var metadata={};for(var k in extensionRegistryOptions.defaultMetadata)metadata[k]=extensionRegistryOptions.defaultMetadata[k];if(opt_metadata){for(var k in opt_metadata)metadata[k]=opt_metadata[k];}var typeInfo=new RegisteredTypeInfo(constructor,metadata);var e=new tr.b.Event('will-register');e.typeInfo=typeInfo;registry.dispatchEvent(e);registry.registeredTypeInfos_.push(typeInfo);e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.pushCleanStateBeforeTest=function(){savedStateStack.push(registry.registeredTypeInfos_);registry.registeredTypeInfos_=[];var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.popCleanStateAfterTest=function(){registry.registeredTypeInfos_=savedStateStack[0];savedStateStack.splice(0,1);var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.findIndexOfRegisteredConstructor=function(constructor){for(var i=0;i<registry.registeredTypeInfos_.length;i++)Iif(registry.registeredTypeInfos_[i].constructor==constructor)return i;return undefined;};registry.unregister=function(constructor){var foundIndex=registry.findIndexOfRegisteredConstructor(constructor);if(foundIndex===undefined)throw new Error(constructor+' not registered');registry.registeredTypeInfos_.splice(foundIndex,1);var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.getAllRegisteredTypeInfos=function(){return registry.registeredTypeInfos_;};registry.findTypeInfo=function(constructor){var foundIndex=this.findIndexOfRegisteredConstructor(constructor);if(foundIndex!==undefined)return this.registeredTypeInfos_[foundIndex];return undefined;};registry.findTypeInfoMatching=function(predicate,opt_this){opt_this=opt_this?opt_this:undefined;for(var i=0;i<registry.registeredTypeInfos_.length;++i){var typeInfo=registry.registeredTypeInfos_[i];if(predicate.call(opt_this,typeInfo))return typeInfo;}return extensionRegistryOptions.defaultTypeInfo;};registry.findTypeInfoWithName=function(name){if(typeof name!=='string')throw new Error('Name is not a string.');var typeInfo=registry.findTypeInfoMatching(function(ti){return ti.constructor.name===name;});if(typeInfo)return typeInfo;return undefined;};}return{_decorateBasicExtensionRegistry:decorateBasicExtensionRegistry};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/extension_registry_type_based.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/extension_registry_type_based.js

Statements: 48.35% (44 / 91)      Branches: 41.18% (14 / 34)      Functions: 50% (7 / 14)      Lines: 100% (1 / 1)      Ignored: none     

1 259  
"use strict";require("./category_util.js");require("./event.js");require("./extension_registry_base.js");'use strict';global.tr.exportTo('tr.b',function(){var getCategoryParts=tr.b.getCategoryParts;var RegisteredTypeInfo=tr.b.RegisteredTypeInfo;var ExtensionRegistryOptions=tr.b.ExtensionRegistryOptions;function decorateTypeBasedExtensionRegistry(registry,extensionRegistryOptions){var savedStateStack=[];registry.registeredTypeInfos_=[];registry.categoryPartToTypeInfoMap_=new Map();registry.typeNameToTypeInfoMap_=new Map();registry.register=function(constructor,metadata){extensionRegistryOptions.validateConstructor(constructor);var typeInfo=new RegisteredTypeInfo(constructor,metadata||extensionRegistryOptions.defaultMetadata);typeInfo.typeNames=[];typeInfo.categoryParts=[];Iif(metadata&&metadata.typeName)typeInfo.typeNames.push(metadata.typeName);Eif(metadata&&metadata.typeNames){typeInfo.typeNames.push.apply(typeInfo.typeNames,metadata.typeNames);}Eif(metadata&&metadata.categoryParts){typeInfo.categoryParts.push.apply(typeInfo.categoryParts,metadata.categoryParts);}Iif(typeInfo.typeNames.length===0&&typeInfo.categoryParts.length===0)throw new Error('typeName or typeNames must be provided');typeInfo.typeNames.forEach(function(typeName){Iif(registry.typeNameToTypeInfoMap_.has(typeName))throw new Error('typeName '+typeName+' already registered');});typeInfo.categoryParts.forEach(function(categoryPart){Iif(registry.categoryPartToTypeInfoMap_.has(categoryPart)){throw new Error('categoryPart '+categoryPart+' already registered');}});var e=new tr.b.Event('will-register');e.typeInfo=typeInfo;registry.dispatchEvent(e);typeInfo.typeNames.forEach(function(typeName){registry.typeNameToTypeInfoMap_.set(typeName,typeInfo);});typeInfo.categoryParts.forEach(function(categoryPart){registry.categoryPartToTypeInfoMap_.set(categoryPart,typeInfo);});registry.registeredTypeInfos_.push(typeInfo);var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.pushCleanStateBeforeTest=function(){savedStateStack.push({registeredTypeInfos:registry.registeredTypeInfos_,typeNameToTypeInfoMap:registry.typeNameToTypeInfoMap_,categoryPartToTypeInfoMap:registry.categoryPartToTypeInfoMap_});registry.registeredTypeInfos_=[];registry.typeNameToTypeInfoMap_=new Map();registry.categoryPartToTypeInfoMap_=new Map();var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.popCleanStateAfterTest=function(){var state=savedStateStack[0];savedStateStack.splice(0,1);registry.registeredTypeInfos_=state.registeredTypeInfos;registry.typeNameToTypeInfoMap_=state.typeNameToTypeInfoMap;registry.categoryPartToTypeInfoMap_=state.categoryPartToTypeInfoMap;var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.unregister=function(constructor){var typeInfoIndex=-1;for(var i=0;i<registry.registeredTypeInfos_.length;i++){if(registry.registeredTypeInfos_[i].constructor==constructor){typeInfoIndex=i;break;}}if(typeInfoIndex===-1)throw new Error(constructor+' not registered');var typeInfo=registry.registeredTypeInfos_[typeInfoIndex];registry.registeredTypeInfos_.splice(typeInfoIndex,1);typeInfo.typeNames.forEach(function(typeName){registry.typeNameToTypeInfoMap_.delete(typeName);});typeInfo.categoryParts.forEach(function(categoryPart){registry.categoryPartToTypeInfoMap_.delete(categoryPart);});var e=new tr.b.Event('registry-changed');registry.dispatchEvent(e);};registry.getTypeInfo=function(category,typeName){if(category){var categoryParts=getCategoryParts(category);for(var i=0;i<categoryParts.length;i++){var categoryPart=categoryParts[i];var typeInfo=registry.categoryPartToTypeInfoMap_.get(categoryPart);if(typeInfo!==undefined)return typeInfo;}}var typeInfo=registry.typeNameToTypeInfoMap_.get(typeName);if(typeInfo!==undefined)return typeInfo;return extensionRegistryOptions.defaultTypeInfo;};registry.getConstructor=function(category,typeName){var typeInfo=registry.getTypeInfo(category,typeName);if(typeInfo)return typeInfo.constructor;return undefined;};}return{_decorateTypeBasedExtensionRegistry:decorateTypeBasedExtensionRegistry};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/guid.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/guid.js

Statements: 57.14% (8 / 14)      Branches: 0% (0 / 2)      Functions: 40% (2 / 5)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){var nextGUID=1;var UUID4_PATTERN='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';var GUID={allocateSimple:function(){return nextGUID++;},getLastSimpleGuid:function(){return nextGUID-1;},allocateUUID4:function(){return UUID4_PATTERN.replace(/[xy]/g,function(c){var r=parseInt(Math.random()*16);if(c==='y')r=(r&3)+8;return r.toString(16);});}};return{GUID:GUID};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/interval_tree.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/interval_tree.js

Statements: 7.69% (10 / 130)      Branches: 0% (0 / 60)      Functions: 2.38% (1 / 42)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function max(a,b){if(a===undefined)return b;if(b===undefined)return a;return Math.max(a,b);}function IntervalTree(beginPositionCb,endPositionCb){this.beginPositionCb_=beginPositionCb;this.endPositionCb_=endPositionCb;this.root_=undefined;this.size_=0;}IntervalTree.prototype={insert:function(datum){var startPosition=this.beginPositionCb_(datum);var endPosition=this.endPositionCb_(datum);var node=new IntervalTreeNode(datum,startPosition,endPosition);this.size_++;this.root_=this.insertNode_(this.root_,node);this.root_.colour=Colour.BLACK;return datum;},insertNode_:function(root,node){if(root===undefined)return node;if(root.leftNode&&root.leftNode.isRed&&root.rightNode&&root.rightNode.isRed)this.flipNodeColour_(root);if(node.key<root.key)root.leftNode=this.insertNode_(root.leftNode,node);else if(node.key===root.key)root.merge(node);else root.rightNode=this.insertNode_(root.rightNode,node);if(root.rightNode&&root.rightNode.isRed&&(root.leftNode===undefined||!root.leftNode.isRed))root=this.rotateLeft_(root);if(root.leftNode&&root.leftNode.isRed&&root.leftNode.leftNode&&root.leftNode.leftNode.isRed)root=this.rotateRight_(root);return root;},rotateRight_:function(node){var sibling=node.leftNode;node.leftNode=sibling.rightNode;sibling.rightNode=node;sibling.colour=node.colour;node.colour=Colour.RED;return sibling;},rotateLeft_:function(node){var sibling=node.rightNode;node.rightNode=sibling.leftNode;sibling.leftNode=node;sibling.colour=node.colour;node.colour=Colour.RED;return sibling;},flipNodeColour_:function(node){node.colour=this.flipColour_(node.colour);node.leftNode.colour=this.flipColour_(node.leftNode.colour);node.rightNode.colour=this.flipColour_(node.rightNode.colour);},flipColour_:function(colour){return colour===Colour.RED?Colour.BLACK:Colour.RED;},updateHighValues:function(){this.updateHighValues_(this.root_);},updateHighValues_:function(node){if(node===undefined)return undefined;node.maxHighLeft=this.updateHighValues_(node.leftNode);node.maxHighRight=this.updateHighValues_(node.rightNode);return max(max(node.maxHighLeft,node.highValue),node.maxHighRight);},validateFindArguments_:function(queryLow,queryHigh){if(queryLow===undefined||queryHigh===undefined)throw new Error('queryLow and queryHigh must be defined');if(typeof queryLow!=='number'||typeof queryHigh!=='number')throw new Error('queryLow and queryHigh must be numbers');},findIntersection:function(queryLow,queryHigh){this.validateFindArguments_(queryLow,queryHigh);if(this.root_===undefined)return[];var ret=[];this.root_.appendIntersectionsInto_(ret,queryLow,queryHigh);return ret;},get size(){return this.size_;},get root(){return this.root_;},dump_:function(){if(this.root_===undefined)return[];return this.root_.dump();}};var Colour={RED:'red',BLACK:'black'};function IntervalTreeNode(datum,lowValue,highValue){this.lowValue_=lowValue;this.data_=[{datum:datum,high:highValue,low:lowValue}];this.colour_=Colour.RED;this.parentNode_=undefined;this.leftNode_=undefined;this.rightNode_=undefined;this.maxHighLeft_=undefined;this.maxHighRight_=undefined;}IntervalTreeNode.prototype={appendIntersectionsInto_:function(ret,queryLow,queryHigh){if(this.lowValue_>=queryHigh){if(!this.leftNode_)return;return this.leftNode_.appendIntersectionsInto_(ret,queryLow,queryHigh);}if(this.maxHighLeft_>queryLow){this.leftNode_.appendIntersectionsInto_(ret,queryLow,queryHigh);}if(this.highValue>queryLow){for(var i=this.data.length-1;i>=0;--i){if(this.data[i].high<queryLow)break;ret.push(this.data[i].datum);}}if(this.rightNode_){this.rightNode_.appendIntersectionsInto_(ret,queryLow,queryHigh);}},get colour(){return this.colour_;},set colour(colour){this.colour_=colour;},get key(){return this.lowValue_;},get lowValue(){return this.lowValue_;},get highValue(){return this.data_[this.data_.length-1].high;},set leftNode(left){this.leftNode_=left;},get leftNode(){return this.leftNode_;},get hasLeftNode(){return this.leftNode_!==undefined;},set rightNode(right){this.rightNode_=right;},get rightNode(){return this.rightNode_;},get hasRightNode(){return this.rightNode_!==undefined;},set parentNode(parent){this.parentNode_=parent;},get parentNode(){return this.parentNode_;},get isRootNode(){return this.parentNode_===undefined;},set maxHighLeft(high){this.maxHighLeft_=high;},get maxHighLeft(){return this.maxHighLeft_;},set maxHighRight(high){this.maxHighRight_=high;},get maxHighRight(){return this.maxHighRight_;},get data(){return this.data_;},get isRed(){return this.colour_===Colour.RED;},merge:function(node){for(var i=0;i<node.data.length;i++)this.data_.push(node.data[i]);this.data_.sort(function(a,b){return a.high-b.high;});},dump:function(){var ret={};if(this.leftNode_)ret['left']=this.leftNode_.dump();ret['data']=this.data_.map(function(d){return[d.low,d.high];});if(this.rightNode_)ret['right']=this.rightNode_.dump();return ret;}};return{IntervalTree:IntervalTree};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/iteration_helpers.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/iteration_helpers.js

Statements: 21.74% (45 / 207)      Branches: 2.5% (2 / 80)      Functions: 13.79% (4 / 29)      Lines: 100% (1 / 1)      Ignored: none     

1 259  
"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function asArray(x){var values=[];if(x[Symbol.iterator])for(var value of x)values.push(value);else for(var i=0;i<x.length;i++)values.push(x[i]);return values;}function getOnlyElement(iterable){var iterator=iterable[Symbol.iterator]();var firstIteration=iterator.next();if(firstIteration.done)throw new Error('getOnlyElement was passed an empty iterable.');var secondIteration=iterator.next();if(!secondIteration.done)throw new Error('getOnlyElement was passed an iterable with multiple elements.');return firstIteration.value;}function getFirstElement(iterable){var iterator=iterable[Symbol.iterator]();var result=iterator.next();if(result.done)throw new Error('getFirstElement was passed an empty iterable.');return result.value;}function compareArrays(x,y,elementCmp){var minLength=Math.min(x.length,y.length);for(var i=0;i<minLength;i++){var tmp=elementCmp(x[i],y[i]);if(tmp)return tmp;}if(x.length==y.length)return 0;if(x[i]===undefined)return-1;return 1;}function comparePossiblyUndefinedValues(x,y,cmp,opt_this){if(x!==undefined&&y!==undefined)return cmp.call(opt_this,x,y);if(x!==undefined)return-1;if(y!==undefined)return 1;return 0;}function compareNumericWithNaNs(x,y){if(!isNaN(x)&&!isNaN(y))return x-y;if(isNaN(x))return 1;if(isNaN(y))return-1;return 0;}function concatenateArrays(){var values=[];for(var i=0;i<arguments.length;i++){if(!(arguments[i]instanceof Array))throw new Error('Arguments '+i+'is not an array');values.push.apply(values,arguments[i]);}return values;}function concatenateObjects(){var result={};for(var i=0;i<arguments.length;i++){var object=arguments[i];for(var j in object){result[j]=object[j];}}return result;}function cloneDictionary(dict){var clone={};for(var k in dict){clone[k]=dict[k];}return clone;}function dictionaryKeys(dict){var keys=[];for(var key in dict)keys.push(key);return keys;}function dictionaryValues(dict){var values=[];for(var key in dict)values.push(dict[key]);return values;}function dictionaryLength(dict){var n=0;for(var key in dict)n++;return n;}function dictionaryContainsValue(dict,value){for(var key in dict)if(dict[key]===value)return true;return false;}function every(iterable,predicate){for(var x of iterable)if(!predicate(x))return false;return true;}function group(ary,callback,opt_this,opt_arrayConstructor){var arrayConstructor=opt_arrayConstructor||Array;var results={};for(var element of ary){var key=callback.call(opt_this,element);if(!(key in results))results[key]=new arrayConstructor();results[key].push(element);}return results;}function groupIntoMap(ary,callback,opt_this,opt_arrayConstructor){var arrayConstructor=opt_arrayConstructor||Array;var results=new Map();for(var element of ary){var key=callback.call(opt_this,element);var items=results.get(key);if(items===undefined){items=new arrayConstructor();results.set(key,items);}items.push(element);}return results;}function iterItems(dict,fn,opt_this){opt_this=opt_this||this;var keys=Object.keys(dict);for(var i=0;i<keys.length;i++){var key=keys[i];fn.call(opt_this,key,dict[key]);}}function mapItems(dict,fn,opt_this){opt_this=opt_this||this;var result={};var keys=Object.keys(dict);for(var i=0;i<keys.length;i++){var key=keys[i];result[key]=fn.call(opt_this,key,dict[key]);}return result;}function filterItems(dict,predicate,opt_this){opt_this=opt_this||this;var result={};var keys=Object.keys(dict);for(var i=0;i<keys.length;i++){var key=keys[i];var value=dict[key];if(predicate.call(opt_this,key,value))result[key]=value;}return result;}function iterObjectFieldsRecursively(object,func){if(!(object instanceof Object))return;if(object instanceof Array){for(var i=0;i<object.length;i++){func(object,i,object[i]);iterObjectFieldsRecursively(object[i],func);}return;}for(var key in object){var value=object[key];func(object,key,value);iterObjectFieldsRecursively(value,func);}}function invertArrayOfDicts(array,opt_dictGetter,opt_this){opt_this=opt_this||this;var result={};for(var i=0;i<array.length;i++){var item=array[i];if(item===undefined)continue;var dict=opt_dictGetter?opt_dictGetter.call(opt_this,item):item;if(dict===undefined)continue;for(var key in dict){var valueList=result[key];if(valueList===undefined)result[key]=valueList=new Array(array.length);valueList[i]=dict[key];}}return result;}function arrayToDict(array,valueToKeyFn,opt_this){opt_this=opt_this||this;var result={};var length=array.length;for(var i=0;i<length;i++){var value=array[i];var key=valueToKeyFn.call(opt_this,value);result[key]=value;}return result;}function identity(d){return d;}function findFirstIndexInArray(ary,opt_func,opt_this){var func=opt_func||identity;for(var i=0;i<ary.length;i++){if(func.call(opt_this,ary[i],i))return i;}return-1;}function findFirstInArray(ary,opt_func,opt_this){var i=findFirstIndexInArray(ary,opt_func,opt_func);if(i===-1)return undefined;return ary[i];}function findFirstKeyInDictMatching(dict,opt_func,opt_this){var func=opt_func||identity;for(var key in dict){if(func.call(opt_this,key,dict[key]))return key;}return undefined;}function mapValues(map){var values=[];for(var value of map.values())values.push(value);return values;}function iterMapItems(map,fn,opt_this){opt_this=opt_this||this;for(var key of map.keys())fn.call(opt_this,key,map.get(key));}return{asArray:asArray,concatenateArrays:concatenateArrays,concatenateObjects:concatenateObjects,compareArrays:compareArrays,comparePossiblyUndefinedValues:comparePossiblyUndefinedValues,compareNumericWithNaNs:compareNumericWithNaNs,cloneDictionary:cloneDictionary,dictionaryLength:dictionaryLength,dictionaryKeys:dictionaryKeys,dictionaryValues:dictionaryValues,dictionaryContainsValue:dictionaryContainsValue,every:every,getOnlyElement:getOnlyElement,getFirstElement:getFirstElement,group:group,groupIntoMap:groupIntoMap,iterItems:iterItems,mapItems:mapItems,filterItems:filterItems,iterObjectFieldsRecursively:iterObjectFieldsRecursively,invertArrayOfDicts:invertArrayOfDicts,arrayToDict:arrayToDict,identity:identity,findFirstIndexInArray:findFirstIndexInArray,findFirstInArray:findFirstInArray,findFirstKeyInDictMatching:findFirstKeyInDictMatching,mapValues:mapValues,iterMapItems:iterMapItems};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/math.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/math.js

Statements: 40% (34 / 85)      Branches: 8.33% (1 / 12)      Functions: 15.79% (3 / 19)      Lines: 100% (1 / 1)      Ignored: none     

1 24  
"use strict";require("./base.js");'use strict';(function(){Eif(tr.isNode){var glMatrixAbsPath=HTMLImportsLoader.hrefToAbsolutePath('/gl-matrix-min.js');var glMatrixModule=require(glMatrixAbsPath);for(var exportName in glMatrixModule){global[exportName]=glMatrixModule[exportName];}}})(this);'use strict';global.tr.exportTo('tr.b',function(){function approximately(x,y,delta){if(delta===undefined)delta=1e-9;return Math.abs(x-y)<delta;}function clamp(x,lo,hi){return Math.min(Math.max(x,lo),hi);}function lerp(percentage,lo,hi){var range=hi-lo;return lo+percentage*range;}function normalize(value,lo,hi){return(value-lo)/(hi-lo);}function deg2rad(deg){return Math.PI*deg/180.0;}function erf(x){var sign=x>=0?1:-1;x=Math.abs(x);var a1=0.254829592;var a2=-0.284496736;var a3=1.421413741;var a4=-1.453152027;var a5=1.061405429;var p=0.3275911;var t=1.0/(1.0+p*x);var y=1.0-((((a5*t+a4)*t+a3)*t+a2)*t+a1)*t*Math.exp(-x*x);return sign*y;}var tmpVec2=vec2.create();var tmpVec2b=vec2.create();var tmpVec4=vec4.create();var tmpMat2d=mat2d.create();vec2.createFromArray=function(arr){if(arr.length!=2)throw new Error('Should be length 2');var v=vec2.create();vec2.set(v,arr[0],arr[1]);return v;};vec2.createXY=function(x,y){var v=vec2.create();vec2.set(v,x,y);return v;};vec2.toString=function(a){return'['+a[0]+', '+a[1]+']';};vec2.addTwoScaledUnitVectors=function(out,u1,scale1,u2,scale2){vec2.scale(tmpVec2,u1,scale1);vec2.scale(tmpVec2b,u2,scale2);vec2.add(out,tmpVec2,tmpVec2b);};vec2.interpolatePiecewiseFunction=function(points,x){if(x<points[0][0])return points[0][1];for(var i=1;i<points.length;++i){if(x<points[i][0]){var percent=normalize(x,points[i-1][0],points[i][0]);return lerp(percent,points[i-1][1],points[i][1]);}}return points[points.length-1][1];};vec3.createXYZ=function(x,y,z){var v=vec3.create();vec3.set(v,x,y,z);return v;};vec3.toString=function(a){return'vec3('+a[0]+', '+a[1]+', '+a[2]+')';};mat2d.translateXY=function(out,x,y){vec2.set(tmpVec2,x,y);mat2d.translate(out,out,tmpVec2);};mat2d.scaleXY=function(out,x,y){vec2.set(tmpVec2,x,y);mat2d.scale(out,out,tmpVec2);};vec4.unitize=function(out,a){out[0]=a[0]/a[3];out[1]=a[1]/a[3];out[2]=a[2]/a[3];out[3]=1;return out;};vec2.copyFromVec4=function(out,a){vec4.unitize(tmpVec4,a);vec2.copy(out,tmpVec4);};return{approximately:approximately,clamp:clamp,lerp:lerp,normalize:normalize,deg2rad:deg2rad,erf:erf};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/multi_dimensional_view.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/multi_dimensional_view.js

Statements: 6.91% (17 / 246)      Branches: 0% (0 / 67)      Functions: 3.85% (1 / 26)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function MultiDimensionalViewNode(title,valueCount){this.title=title;var dimensions=title.length;this.children=new Array(dimensions);for(var i=0;i<dimensions;i++)this.children[i]=new Map();this.values=new Array(valueCount);for(var v=0;v<valueCount;v++)this.values[v]={self:0,total:0,totalState:NOT_PROVIDED};}MultiDimensionalViewNode.TotalState={NOT_PROVIDED:0,LOWER_BOUND:1,EXACT:2};var NOT_PROVIDED=MultiDimensionalViewNode.TotalState.NOT_PROVIDED;var LOWER_BOUND=MultiDimensionalViewNode.TotalState.LOWER_BOUND;var EXACT=MultiDimensionalViewNode.TotalState.EXACT;MultiDimensionalViewNode.prototype={get subRows(){return tr.b.mapValues(this.children[0]);}};function MultiDimensionalViewBuilder(dimensions,valueCount){if(typeof dimensions!=='number'||dimensions<0)throw new Error('Dimensions must be a non-negative number');this.dimensions_=dimensions;if(typeof valueCount!=='number'||valueCount<0)throw new Error('Number of values must be a non-negative number');this.valueCount_=valueCount;this.buildRoot_=this.createRootNode_();this.topDownTreeViewRoot_=undefined;this.topDownHeavyViewRoot_=undefined;this.bottomUpHeavyViewNode_=undefined;this.maxDimensionDepths_=new Array(dimensions);for(var d=0;d<dimensions;d++)this.maxDimensionDepths_[d]=0;}MultiDimensionalViewBuilder.ValueKind={SELF:0,TOTAL:1};MultiDimensionalViewBuilder.ViewType={TOP_DOWN_TREE_VIEW:0,TOP_DOWN_HEAVY_VIEW:1,BOTTOM_UP_HEAVY_VIEW:2};MultiDimensionalViewBuilder.prototype={addPath:function(path,values,valueKind){if(this.buildRoot_===undefined){throw new Error('Paths cannot be added after either view has been built');}if(path.length!==this.dimensions_)throw new Error('Path must be '+this.dimensions_+'-dimensional');if(values.length!==this.valueCount_)throw new Error('Must provide '+this.valueCount_+' values');var isTotal;switch(valueKind){case MultiDimensionalViewBuilder.ValueKind.SELF:isTotal=false;break;case MultiDimensionalViewBuilder.ValueKind.TOTAL:isTotal=true;break;default:throw new Error('Invalid value kind: '+valueKind);}var node=this.buildRoot_;for(var d=0;d<path.length;d++){var singleDimensionPath=path[d];var singleDimensionPathLength=singleDimensionPath.length;this.maxDimensionDepths_[d]=Math.max(this.maxDimensionDepths_[d],singleDimensionPathLength);for(var i=0;i<singleDimensionPathLength;i++)node=this.getOrCreateChildNode_(node,d,singleDimensionPath[i]);}for(var v=0;v<this.valueCount_;v++){var addedValue=values[v];if(addedValue===undefined)continue;var nodeValue=node.values[v];if(isTotal){nodeValue.total+=addedValue;nodeValue.totalState=EXACT;}else{nodeValue.self+=addedValue;nodeValue.totalState=Math.max(nodeValue.totalState,LOWER_BOUND);}}},buildView:function(viewType){switch(viewType){case MultiDimensionalViewBuilder.ViewType.TOP_DOWN_TREE_VIEW:return this.buildTopDownTreeView();case MultiDimensionalViewBuilder.ViewType.TOP_DOWN_HEAVY_VIEW:return this.buildTopDownHeavyView();case MultiDimensionalViewBuilder.ViewType.BOTTOM_UP_HEAVY_VIEW:return this.buildBottomUpHeavyView();default:throw new Error('Unknown multi-dimensional view type: '+viewType);}},buildTopDownTreeView:function(){if(this.topDownTreeViewRoot_===undefined){var treeViewRoot=this.buildRoot_;this.buildRoot_=undefined;this.setUpMissingChildRelationships_(treeViewRoot,0);this.finalizeTotalValues_(treeViewRoot,0,new WeakMap());this.topDownTreeViewRoot_=treeViewRoot;}return this.topDownTreeViewRoot_;},buildTopDownHeavyView:function(){if(this.topDownHeavyViewRoot_===undefined){this.topDownHeavyViewRoot_=this.buildGenericHeavyView_(this.addDimensionToTopDownHeavyViewNode_.bind(this));}return this.topDownHeavyViewRoot_;},buildBottomUpHeavyView:function(){if(this.bottomUpHeavyViewNode_===undefined){this.bottomUpHeavyViewNode_=this.buildGenericHeavyView_(this.addDimensionToBottomUpHeavyViewNode_.bind(this));}return this.bottomUpHeavyViewNode_;},createRootNode_:function(){return new MultiDimensionalViewNode(new Array(this.dimensions_),this.valueCount_);},getOrCreateChildNode_:function(parentNode,dimension,childDimensionTitle){if(dimension<0||dimension>=this.dimensions_)throw new Error('Invalid dimension');var dimensionChildren=parentNode.children[dimension];var childNode=dimensionChildren.get(childDimensionTitle);if(childNode!==undefined)return childNode;var childTitle=parentNode.title.slice();childTitle[dimension]=childDimensionTitle;childNode=new MultiDimensionalViewNode(childTitle,this.valueCount_);dimensionChildren.set(childDimensionTitle,childNode);return childNode;},setUpMissingChildRelationships_:function(node,firstDimensionToSetUp){for(var d=firstDimensionToSetUp;d<this.dimensions_;d++){var currentDimensionChildTitles=new Set(node.children[d].keys());for(var i=0;i<d;i++){for(var previousDimensionChildNode of node.children[i].values()){for(var previousDimensionGrandChildTitle of previousDimensionChildNode.children[d].keys()){currentDimensionChildTitles.add(previousDimensionGrandChildTitle);}}}for(var currentDimensionChildTitle of currentDimensionChildTitles){var currentDimensionChildNode=this.getOrCreateChildNode_(node,d,currentDimensionChildTitle);for(var i=0;i<d;i++){for(var previousDimensionChildNode of node.children[i].values()){var previousDimensionGrandChildNode=previousDimensionChildNode.children[d].get(currentDimensionChildTitle);if(previousDimensionGrandChildNode!==undefined){currentDimensionChildNode.children[i].set(previousDimensionChildNode.title[i],previousDimensionGrandChildNode);}}}this.setUpMissingChildRelationships_(currentDimensionChildNode,d);}}},finalizeTotalValues_:function(node,firstDimensionToFinalize,dimensionalSelfSumsMap){var dimensionalSelfSums=new Array(this.dimensions_);var minResidual=new Array(this.valueCount_);for(var v=0;v<this.valueCount_;v++)minResidual[v]=0;var nodeValues=node.values;var nodeSelfSums=new Array(this.valueCount_);for(var v=0;v<this.valueCount_;v++)nodeSelfSums[v]=nodeValues[v].self;for(var d=0;d<this.dimensions_;d++){var childResidualSums=new Array(this.valueCount_);for(var v=0;v<this.valueCount_;v++)childResidualSums[v]=0;for(var childNode of node.children[d].values()){if(d>=firstDimensionToFinalize)this.finalizeTotalValues_(childNode,d,dimensionalSelfSumsMap);var childNodeSelfSums=dimensionalSelfSumsMap.get(childNode);var childNodeValues=childNode.values;for(var v=0;v<this.valueCount_;v++){nodeSelfSums[v]+=childNodeSelfSums[d][v];var residual=childNodeValues[v].total-childNodeSelfSums[this.dimensions_-1][v];childResidualSums[v]+=residual;if(childNodeValues[v].totalState>NOT_PROVIDED){nodeValues[v].totalState=Math.max(nodeValues[v].totalState,LOWER_BOUND);}}}dimensionalSelfSums[d]=nodeSelfSums.slice();for(var v=0;v<this.valueCount_;v++)minResidual[v]=Math.max(minResidual[v],childResidualSums[v]);}for(var v=0;v<this.valueCount_;v++){nodeValues[v].total=Math.max(nodeValues[v].total,nodeSelfSums[v]+minResidual[v]);}if(dimensionalSelfSumsMap.has(node))throw new Error('Internal error: Node finalized more than once');dimensionalSelfSumsMap.set(node,dimensionalSelfSums);},buildGenericHeavyView_:function(treeViewNodeHandler){var treeViewRoot=this.buildTopDownTreeView();var heavyViewRoot=this.createRootNode_();heavyViewRoot.values=treeViewRoot.values;var recursionDepthTrackers=new Array(this.dimensions_);for(var d=0;d<this.dimensions_;d++){recursionDepthTrackers[d]=new RecursionDepthTracker(this.maxDimensionDepths_[d],d);}this.addDimensionsToGenericHeavyViewNode_(treeViewRoot,heavyViewRoot,0,recursionDepthTrackers,false,treeViewNodeHandler);this.setUpMissingChildRelationships_(heavyViewRoot,0);return heavyViewRoot;},addDimensionsToGenericHeavyViewNode_:function(treeViewParentNode,heavyViewParentNode,startDimension,recursionDepthTrackers,previousDimensionsRecursive,treeViewNodeHandler){for(var d=startDimension;d<this.dimensions_;d++){this.addDimensionDescendantsToGenericHeavyViewNode_(treeViewParentNode,heavyViewParentNode,d,recursionDepthTrackers,previousDimensionsRecursive,treeViewNodeHandler);}},addDimensionDescendantsToGenericHeavyViewNode_:function(treeViewParentNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive,treeViewNodeHandler){var treeViewChildren=treeViewParentNode.children[currentDimension];var recursionDepthTracker=recursionDepthTrackers[currentDimension];for(var treeViewChildNode of treeViewChildren.values()){recursionDepthTracker.push(treeViewChildNode);treeViewNodeHandler(treeViewChildNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive);this.addDimensionDescendantsToGenericHeavyViewNode_(treeViewChildNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive,treeViewNodeHandler);recursionDepthTracker.pop();}},addDimensionToTopDownHeavyViewNode_:function(treeViewChildNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive){this.addDimensionToTopDownHeavyViewNodeRecursively_(treeViewChildNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive,1);},addDimensionToTopDownHeavyViewNodeRecursively_:function(treeViewChildNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive,subTreeDepth){var recursionDepthTracker=recursionDepthTrackers[currentDimension];var currentDimensionRecursive=subTreeDepth<=recursionDepthTracker.recursionDepth;var currentOrPreviousDimensionsRecursive=currentDimensionRecursive||previousDimensionsRecursive;var dimensionTitle=treeViewChildNode.title[currentDimension];var heavyViewChildNode=this.getOrCreateChildNode_(heavyViewParentNode,currentDimension,dimensionTitle);this.addNodeValues_(treeViewChildNode,heavyViewChildNode,!currentOrPreviousDimensionsRecursive);this.addDimensionsToGenericHeavyViewNode_(treeViewChildNode,heavyViewChildNode,currentDimension+1,recursionDepthTrackers,currentOrPreviousDimensionsRecursive,this.addDimensionToTopDownHeavyViewNode_.bind(this));for(var treeViewGrandChildNode of treeViewChildNode.children[currentDimension].values()){recursionDepthTracker.push(treeViewGrandChildNode);this.addDimensionToTopDownHeavyViewNodeRecursively_(treeViewGrandChildNode,heavyViewChildNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive,subTreeDepth+1);recursionDepthTracker.pop();}},addDimensionToBottomUpHeavyViewNode_:function(treeViewChildNode,heavyViewParentNode,currentDimension,recursionDepthTrackers,previousDimensionsRecursive){var recursionDepthTracker=recursionDepthTrackers[currentDimension];var bottomIndex=recursionDepthTracker.bottomIndex;var topIndex=recursionDepthTracker.topIndex;var firstNonRecursiveIndex=bottomIndex+recursionDepthTracker.recursionDepth;var viewNodePath=recursionDepthTracker.viewNodePath;var trackerAncestorNode=recursionDepthTracker.trackerAncestorNode;var heavyViewDescendantNode=heavyViewParentNode;for(var i=bottomIndex;i<topIndex;i++){var treeViewAncestorNode=viewNodePath[i];var dimensionTitle=treeViewAncestorNode.title[currentDimension];heavyViewDescendantNode=this.getOrCreateChildNode_(heavyViewDescendantNode,currentDimension,dimensionTitle);var currentDimensionRecursive=i<firstNonRecursiveIndex;var currentOrPreviousDimensionsRecursive=currentDimensionRecursive||previousDimensionsRecursive;this.addNodeValues_(treeViewChildNode,heavyViewDescendantNode,!currentOrPreviousDimensionsRecursive);this.addDimensionsToGenericHeavyViewNode_(treeViewChildNode,heavyViewDescendantNode,currentDimension+1,recursionDepthTrackers,currentOrPreviousDimensionsRecursive,this.addDimensionToBottomUpHeavyViewNode_.bind(this));}},addNodeValues_:function(sourceNode,targetNode,addTotal){var targetNodeValues=targetNode.values;var sourceNodeValues=sourceNode.values;for(var v=0;v<this.valueCount_;v++){var targetNodeValue=targetNodeValues[v];var sourceNodeValue=sourceNodeValues[v];targetNodeValue.self+=sourceNodeValue.self;if(addTotal){targetNodeValue.total+=sourceNodeValue.total;if(sourceNodeValue.totalState>NOT_PROVIDED){targetNodeValue.totalState=Math.max(targetNodeValue.totalState,LOWER_BOUND);}}}}};function RecursionDepthTracker(maxDepth,dimension){this.titlePath=new Array(maxDepth);this.viewNodePath=new Array(maxDepth);this.bottomIndex=this.topIndex=maxDepth;this.dimension_=dimension;this.currentTrackerNode_=this.createNode_(0,undefined);}RecursionDepthTracker.prototype={push:function(viewNode){if(this.bottomIndex===0)throw new Error('Cannot push to a full tracker');var title=viewNode.title[this.dimension_];this.bottomIndex--;this.titlePath[this.bottomIndex]=title;this.viewNodePath[this.bottomIndex]=viewNode;var childTrackerNode=this.currentTrackerNode_.children.get(title);if(childTrackerNode!==undefined){this.currentTrackerNode_=childTrackerNode;return;}var maxLengths=zFunction(this.titlePath,this.bottomIndex);var recursionDepth=0;for(var i=0;i<maxLengths.length;i++)recursionDepth=Math.max(recursionDepth,maxLengths[i]);childTrackerNode=this.createNode_(recursionDepth,this.currentTrackerNode_);this.currentTrackerNode_.children.set(title,childTrackerNode);this.currentTrackerNode_=childTrackerNode;},pop:function(){if(this.bottomIndex===this.topIndex)throw new Error('Cannot pop from an empty tracker');this.titlePath[this.bottomIndex]=undefined;this.viewNodePath[this.bottomIndex]=undefined;this.bottomIndex++;this.currentTrackerNode_=this.currentTrackerNode_.parent;},get recursionDepth(){return this.currentTrackerNode_.recursionDepth;},createNode_:function(recursionDepth,parent){return{recursionDepth:recursionDepth,parent:parent,children:new Map()};}};function zFunction(list,startIndex){var n=list.length-startIndex;if(n===0)return[];var z=new Array(n);z[0]=0;for(var i=1,left=0,right=0;i<n;++i){var maxLength;if(i<=right)maxLength=Math.min(right-i+1,z[i-left]);else maxLength=0;while(i+maxLength<n&&list[startIndex+maxLength]===list[startIndex+i+maxLength]){++maxLength;}if(i+maxLength-1>right){left=i;right=i+maxLength-1;}z[i]=maxLength;}return z;}return{MultiDimensionalViewBuilder:MultiDimensionalViewBuilder,MultiDimensionalViewNode:MultiDimensionalViewNode,RecursionDepthTracker:RecursionDepthTracker,zFunction:zFunction};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/piecewise_linear_function.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/piecewise_linear_function.js

Statements: 14.52% (9 / 62)      Branches: 0% (0 / 24)      Functions: 6.67% (1 / 15)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){var PERCENTILE_PRECISION=1e-7;function PiecewiseLinearFunction(){this.pieces=[];}PiecewiseLinearFunction.prototype={push:function(x1,y1,x2,y2){if(x1>=x2)throw new Error('Invalid segment');if(this.pieces.length>0&&this.pieces[this.pieces.length-1].x2>x1){throw new Error('Potentially overlapping segments');}if(x1<x2)this.pieces.push(new Piece(x1,y1,x2,y2));},partBelow:function(y){return this.pieces.reduce((acc,p)=>acc+p.partBelow(y),0);},get min(){return this.pieces.reduce((acc,p)=>Math.min(acc,p.min),Infinity);},get max(){return this.pieces.reduce((acc,p)=>Math.max(acc,p.max),-Infinity);},get average(){var weightedSum=0;var totalWeight=0;this.pieces.forEach(function(piece){weightedSum+=piece.width*piece.average;totalWeight+=piece.width;});if(totalWeight===0)return 0;return weightedSum/totalWeight;},percentile:function(percent){if(!(percent>=0&&percent<=1))throw new Error('percent must be [0,1]');var lower=this.min;var upper=this.max;var total=this.partBelow(upper);if(total===0)return 0;while(upper-lower>PERCENTILE_PRECISION){var middle=(lower+upper)/2;var below=this.partBelow(middle);if(below/total<percent)lower=middle;else upper=middle;}return(lower+upper)/2;}};function Piece(x1,y1,x2,y2){this.x1=x1;this.y1=y1;this.x2=x2;this.y2=y2;}Piece.prototype={partBelow:function(y){var width=this.width;if(width===0)return 0;var minY=this.min;var maxY=this.max;if(y>=maxY)return width;if(y<minY)return 0;return(y-minY)/(maxY-minY)*width;},get min(){return Math.min(this.y1,this.y2);},get max(){return Math.max(this.y1,this.y2);},get average(){return(this.y1+this.y2)/2;},get width(){return this.x2-this.x1;}};return{PiecewiseLinearFunction:PiecewiseLinearFunction};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/quad.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/quad.js

Statements: 22.83% (29 / 127)      Branches: 0% (0 / 14)      Functions: 5.26% (1 / 19)      Lines: 100% (1 / 1)      Ignored: none     

1 28  
"use strict";require("./base.js");require("./math.js");'use strict';global.tr.exportTo('tr.b',function(){var tmpVec2s=[];for(var i=0;i<8;i++)tmpVec2s[i]=vec2.create();var tmpVec2a=vec4.create();var tmpVec4a=vec4.create();var tmpVec4b=vec4.create();var tmpMat4=mat4.create();var tmpMat4b=mat4.create();var p00=vec2.createXY(0,0);var p10=vec2.createXY(1,0);var p01=vec2.createXY(0,1);var p11=vec2.createXY(1,1);var lerpingVecA=vec2.create();var lerpingVecB=vec2.create();function lerpVec2(out,a,b,amt){vec2.scale(lerpingVecA,a,amt);vec2.scale(lerpingVecB,b,1-amt);vec2.add(out,lerpingVecA,lerpingVecB);vec2.normalize(out,out);return out;}function Quad(){this.p1=vec2.create();this.p2=vec2.create();this.p3=vec2.create();this.p4=vec2.create();}Quad.fromXYWH=function(x,y,w,h){var q=new Quad();vec2.set(q.p1,x,y);vec2.set(q.p2,x+w,y);vec2.set(q.p3,x+w,y+h);vec2.set(q.p4,x,y+h);return q;};Quad.fromRect=function(r){return new Quad.fromXYWH(r.x,r.y,r.width,r.height);};Quad.from4Vecs=function(p1,p2,p3,p4){var q=new Quad();vec2.set(q.p1,p1[0],p1[1]);vec2.set(q.p2,p2[0],p2[1]);vec2.set(q.p3,p3[0],p3[1]);vec2.set(q.p4,p4[0],p4[1]);return q;};Quad.from8Array=function(arr){if(arr.length!=8)throw new Error('Array must be 8 long');var q=new Quad();q.p1[0]=arr[0];q.p1[1]=arr[1];q.p2[0]=arr[2];q.p2[1]=arr[3];q.p3[0]=arr[4];q.p3[1]=arr[5];q.p4[0]=arr[6];q.p4[1]=arr[7];return q;};Quad.prototype={pointInside:function(point){return pointInImplicitQuad(point,this.p1,this.p2,this.p3,this.p4);},boundingRect:function(){var x0=Math.min(this.p1[0],this.p2[0],this.p3[0],this.p4[0]);var y0=Math.min(this.p1[1],this.p2[1],this.p3[1],this.p4[1]);var x1=Math.max(this.p1[0],this.p2[0],this.p3[0],this.p4[0]);var y1=Math.max(this.p1[1],this.p2[1],this.p3[1],this.p4[1]);return new tr.b.Rect.fromXYWH(x0,y0,x1-x0,y1-y0);},clone:function(){var q=new Quad();vec2.copy(q.p1,this.p1);vec2.copy(q.p2,this.p2);vec2.copy(q.p3,this.p3);vec2.copy(q.p4,this.p4);return q;},scale:function(s){var q=new Quad();this.scaleFast(q,s);return q;},scaleFast:function(dstQuad,s){vec2.copy(dstQuad.p1,this.p1,s);vec2.copy(dstQuad.p2,this.p2,s);vec2.copy(dstQuad.p3,this.p3,s);vec2.copy(dstQuad.p3,this.p3,s);},isRectangle:function(){var bounds=this.boundingRect();return bounds.x==this.p1[0]&&bounds.y==this.p1[1]&&bounds.width==this.p2[0]-this.p1[0]&&bounds.y==this.p2[1]&&bounds.width==this.p3[0]-this.p1[0]&&bounds.height==this.p3[1]-this.p2[1]&&bounds.x==this.p4[0]&&bounds.height==this.p4[1]-this.p2[1];},projectUnitRect:function(rect){var q=new Quad();this.projectUnitRectFast(q,rect);return q;},projectUnitRectFast:function(dstQuad,rect){var v12=tmpVec2s[0];var v14=tmpVec2s[1];var v23=tmpVec2s[2];var v43=tmpVec2s[3];var l12,l14,l23,l43;vec2.sub(v12,this.p2,this.p1);l12=vec2.length(v12);vec2.scale(v12,v12,1/l12);vec2.sub(v14,this.p4,this.p1);l14=vec2.length(v14);vec2.scale(v14,v14,1/l14);vec2.sub(v23,this.p3,this.p2);l23=vec2.length(v23);vec2.scale(v23,v23,1/l23);vec2.sub(v43,this.p3,this.p4);l43=vec2.length(v43);vec2.scale(v43,v43,1/l43);var b12=tmpVec2s[0];var b14=tmpVec2s[1];var b23=tmpVec2s[2];var b43=tmpVec2s[3];lerpVec2(b12,v12,v43,rect.y);lerpVec2(b43,v12,v43,1-rect.bottom);lerpVec2(b14,v14,v23,rect.x);lerpVec2(b23,v14,v23,1-rect.right);vec2.addTwoScaledUnitVectors(tmpVec2a,b12,l12*rect.x,b14,l14*rect.y);vec2.add(dstQuad.p1,this.p1,tmpVec2a);vec2.addTwoScaledUnitVectors(tmpVec2a,b12,l12*-(1.0-rect.right),b23,l23*rect.y);vec2.add(dstQuad.p2,this.p2,tmpVec2a);vec2.addTwoScaledUnitVectors(tmpVec2a,b43,l43*-(1.0-rect.right),b23,l23*-(1.0-rect.bottom));vec2.add(dstQuad.p3,this.p3,tmpVec2a);vec2.addTwoScaledUnitVectors(tmpVec2a,b43,l43*rect.left,b14,l14*-(1.0-rect.bottom));vec2.add(dstQuad.p4,this.p4,tmpVec2a);},toString:function(){return'Quad('+vec2.toString(this.p1)+', '+vec2.toString(this.p2)+', '+vec2.toString(this.p3)+', '+vec2.toString(this.p4)+')';}};function sign(p1,p2,p3){return(p1[0]-p3[0])*(p2[1]-p3[1])-(p2[0]-p3[0])*(p1[1]-p3[1]);}function pointInTriangle2(pt,p1,p2,p3){var b1=sign(pt,p1,p2)<0.0;var b2=sign(pt,p2,p3)<0.0;var b3=sign(pt,p3,p1)<0.0;return b1==b2&&b2==b3;}function pointInImplicitQuad(point,p1,p2,p3,p4){return pointInTriangle2(point,p1,p2,p3)||pointInTriangle2(point,p1,p3,p4);}return{pointInTriangle2:pointInTriangle2,pointInImplicitQuad:pointInImplicitQuad,Quad:Quad};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/raf.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/raf.js

Statements: 25.47% (27 / 106)      Branches: 0% (0 / 52)      Functions: 5% (1 / 20)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./utils.js");'use strict';global.tr.exportTo('tr.b',function(){var ESTIMATED_IDLE_PERIOD_LENGTH_MILLISECONDS=10;var REQUEST_IDLE_CALLBACK_TIMEOUT_MILLISECONDS=100;var recordRAFStacks=false;var pendingPreAFs=[];var pendingRAFs=[];var pendingIdleCallbacks=[];var currentRAFDispatchList=undefined;var rafScheduled=false;var idleWorkScheduled=false;function scheduleRAF(){if(rafScheduled)return;rafScheduled=true;if(tr.isHeadless){Promise.resolve().then(function(){processRequests(false,0);},function(e){console.log(e.stack);throw e;});}else{if(window.requestAnimationFrame){window.requestAnimationFrame(processRequests.bind(this,false));}else{var delta=Date.now()-window.performance.now();window.webkitRequestAnimationFrame(function(domTimeStamp){processRequests(false,domTimeStamp-delta);});}}}function nativeRequestIdleCallbackSupported(){return!tr.isHeadless&&window.requestIdleCallback;}function scheduleIdleWork(){if(idleWorkScheduled)return;if(!nativeRequestIdleCallbackSupported()){scheduleRAF();return;}idleWorkScheduled=true;window.requestIdleCallback(function(deadline,didTimeout){processIdleWork(false,deadline);},{timeout:REQUEST_IDLE_CALLBACK_TIMEOUT_MILLISECONDS});}function onAnimationFrameError(e,opt_stack){console.log(e.stack);if(tr.isHeadless)throw e;if(opt_stack)console.log(opt_stack);if(e.message)console.error(e.message,e.stack);else console.error(e);}function runTask(task,frameBeginTime){try{task.callback.call(task.context,frameBeginTime);}catch(e){tr.b.onAnimationFrameError(e,task.stack);}}function processRequests(forceAllTasksToRun,frameBeginTime){rafScheduled=false;var currentPreAFs=pendingPreAFs;currentRAFDispatchList=pendingRAFs;pendingPreAFs=[];pendingRAFs=[];var hasRAFTasks=currentPreAFs.length||currentRAFDispatchList.length;for(var i=0;i<currentPreAFs.length;i++)runTask(currentPreAFs[i],frameBeginTime);while(currentRAFDispatchList.length>0)runTask(currentRAFDispatchList.shift(),frameBeginTime);currentRAFDispatchList=undefined;if(!hasRAFTasks&&!nativeRequestIdleCallbackSupported()||forceAllTasksToRun){var rafCompletionDeadline=frameBeginTime+ESTIMATED_IDLE_PERIOD_LENGTH_MILLISECONDS;processIdleWork(forceAllTasksToRun,{timeRemaining:function(){return rafCompletionDeadline-window.performance.now();}});}if(pendingIdleCallbacks.length>0)scheduleIdleWork();}function processIdleWork(forceAllTasksToRun,deadline){idleWorkScheduled=false;while(pendingIdleCallbacks.length>0){runTask(pendingIdleCallbacks.shift());if(!forceAllTasksToRun&&(tr.isHeadless||deadline.timeRemaining()<=0)){break;}}if(pendingIdleCallbacks.length>0)scheduleIdleWork();}function getStack_(){if(!recordRAFStacks)return'';var stackLines=tr.b.stackTrace();stackLines.shift();return stackLines.join('\n');}function requestPreAnimationFrame(callback,opt_this){pendingPreAFs.push({callback:callback,context:opt_this||global,stack:getStack_()});scheduleRAF();}function requestAnimationFrameInThisFrameIfPossible(callback,opt_this){if(!currentRAFDispatchList){requestAnimationFrame(callback,opt_this);return;}currentRAFDispatchList.push({callback:callback,context:opt_this||global,stack:getStack_()});return;}function requestAnimationFrame(callback,opt_this){pendingRAFs.push({callback:callback,context:opt_this||global,stack:getStack_()});scheduleRAF();}function requestIdleCallback(callback,opt_this){pendingIdleCallbacks.push({callback:callback,context:opt_this||global,stack:getStack_()});scheduleIdleWork();}function forcePendingRAFTasksToRun(frameBeginTime){if(!rafScheduled)return;processRequests(false,frameBeginTime);}function forceAllPendingTasksToRunForTest(){if(!rafScheduled&&!idleWorkScheduled)return;processRequests(true,0);}return{onAnimationFrameError:onAnimationFrameError,requestPreAnimationFrame:requestPreAnimationFrame,requestAnimationFrame:requestAnimationFrame,requestAnimationFrameInThisFrameIfPossible:requestAnimationFrameInThisFrameIfPossible,requestIdleCallback:requestIdleCallback,forcePendingRAFTasksToRun:forcePendingRAFTasksToRun,forceAllPendingTasksToRunForTest:forceAllPendingTasksToRunForTest};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/range.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/range.js

Statements: 26.52% (35 / 132)      Branches: 3.75% (3 / 80)      Functions: 20% (7 / 35)      Lines: 100% (1 / 1)      Ignored: none     

1 241  
"use strict";require("./base.js");require("./iteration_helpers.js");require("./math.js");'use strict';global.tr.exportTo('tr.b',function(){function Range(){this.isEmpty_=true;this.min_=undefined;this.max_=undefined;}Range.prototype={__proto__:Object.prototype,reset:function(){this.isEmpty_=true;this.min_=undefined;this.max_=undefined;},get isEmpty(){return this.isEmpty_;},addRange:function(range){if(range.isEmpty)return;this.addValue(range.min);this.addValue(range.max);},addValue:function(value){if(this.isEmpty_){this.max_=value;this.min_=value;this.isEmpty_=false;return;}this.max_=Math.max(this.max_,value);this.min_=Math.min(this.min_,value);},set min(min){this.isEmpty_=false;this.min_=min;},get min(){if(this.isEmpty_)return undefined;return this.min_;},get max(){Iif(this.isEmpty_)return undefined;return this.max_;},set max(max){this.isEmpty_=false;this.max_=max;},get range(){if(this.isEmpty_)return undefined;return this.max_-this.min_;},get center(){return(this.min_+this.max_)*0.5;},get duration(){if(this.isEmpty_)return 0;return this.max_-this.min_;},normalize:function(x){return tr.b.normalize(x,this.min,this.max);},lerp:function(x){return tr.b.lerp(x,this.min,this.max);},equals:function(that){if(this.isEmpty&&that.isEmpty)return true;if(this.isEmpty!=that.isEmpty)return false;return tr.b.approximately(this.min,that.min)&&tr.b.approximately(this.max,that.max);},containsExplicitRangeInclusive:function(min,max){if(this.isEmpty)return false;return this.min_<=min&&max<=this.max_;},containsExplicitRangeExclusive:function(min,max){if(this.isEmpty)return false;return this.min_<min&&max<this.max_;},intersectsExplicitRangeInclusive:function(min,max){if(this.isEmpty)return false;return this.min_<=max&&min<=this.max_;},intersectsExplicitRangeExclusive:function(min,max){if(this.isEmpty)return false;return this.min_<max&&min<this.max_;},containsRangeInclusive:function(range){if(range.isEmpty)return false;return this.containsExplicitRangeInclusive(range.min_,range.max_);},containsRangeExclusive:function(range){if(range.isEmpty)return false;return this.containsExplicitRangeExclusive(range.min_,range.max_);},intersectsRangeInclusive:function(range){if(range.isEmpty)return false;return this.intersectsExplicitRangeInclusive(range.min_,range.max_);},intersectsRangeExclusive:function(range){if(range.isEmpty)return false;return this.intersectsExplicitRangeExclusive(range.min_,range.max_);},findExplicitIntersectionDuration:function(min,max){var min=Math.max(this.min,min);var max=Math.min(this.max,max);if(max<min)return 0;return max-min;},findIntersection:function(range){if(this.isEmpty||range.isEmpty)return new Range();var min=Math.max(this.min,range.min);var max=Math.min(this.max,range.max);if(max<min)return new Range();return Range.fromExplicitRange(min,max);},toJSON:function(){if(this.isEmpty_)return{isEmpty:true};return{isEmpty:false,max:this.max,min:this.min};},filterArray:function(array,opt_keyFunc,opt_this){if(this.isEmpty_)return[];function binSearch(test){var i0=0;var i1=array.length;while(i0<i1){var i=Math.trunc((i0+i1)/2);if(test(i))i1=i;else i0=i+1;}return i1;}var keyFunc=opt_keyFunc||tr.b.identity;function getValue(index){return keyFunc.call(opt_this,array[index]);}var first=binSearch(function(i){return this.min_===undefined||this.min_<=getValue(i);}.bind(this));var last=binSearch(function(i){return this.max_!==undefined&&this.max_<getValue(i);}.bind(this));return array.slice(first,last);}};Range.fromDict=function(d){if(d.isEmpty===true){return new Range();}else if(d.isEmpty===false){var range=new Range();range.min=d.min;range.max=d.max;return range;}else{throw new Error('Not a range');}};Range.fromExplicitRange=function(min,max){var range=new Range();range.min=min;range.max=max;return range;};Range.compareByMinTimes=function(a,b){if(!a.isEmpty&&!b.isEmpty)return a.min_-b.min_;if(a.isEmpty&&!b.isEmpty)return-1;if(!a.isEmpty&&b.isEmpty)return 1;return 0;};Range.PERCENT_RANGE=Range.fromExplicitRange(0,1);Object.freeze(Range.PERCENT_RANGE);return{Range:Range};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/range_utils.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/range_utils.js

Statements: 14.49% (10 / 69)      Branches: 0% (0 / 32)      Functions: 10% (1 / 10)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./base.js");require("./iteration_helpers.js");'use strict';global.tr.exportTo('tr.b',function(){function convertEventsToRanges(events){return events.map(function(event){return tr.b.Range.fromExplicitRange(event.start,event.end);});}function mergeRanges(inRanges,mergeThreshold,mergeFunction){var remainingEvents=inRanges.slice();remainingEvents.sort(function(x,y){return x.min-y.min;});if(remainingEvents.length<=1){var merged=[];if(remainingEvents.length==1){merged.push(mergeFunction(remainingEvents));}return merged;}var mergedEvents=[];var currentMergeBuffer=[];var rightEdge;function beginMerging(){currentMergeBuffer.push(remainingEvents[0]);remainingEvents.splice(0,1);rightEdge=currentMergeBuffer[0].max;}function flushCurrentMergeBuffer(){if(currentMergeBuffer.length==0)return;mergedEvents.push(mergeFunction(currentMergeBuffer));currentMergeBuffer=[];if(remainingEvents.length!=0)beginMerging();}beginMerging();while(remainingEvents.length){var currentEvent=remainingEvents[0];var distanceFromRightEdge=currentEvent.min-rightEdge;if(distanceFromRightEdge<mergeThreshold){rightEdge=Math.max(rightEdge,currentEvent.max);remainingEvents.splice(0,1);currentMergeBuffer.push(currentEvent);continue;}flushCurrentMergeBuffer();}flushCurrentMergeBuffer();return mergedEvents;}function findEmptyRangesBetweenRanges(inRanges,opt_totalRange){if(opt_totalRange&&opt_totalRange.isEmpty)opt_totalRange=undefined;var emptyRanges=[];if(!inRanges.length){if(opt_totalRange)emptyRanges.push(opt_totalRange);return emptyRanges;}inRanges=inRanges.slice();inRanges.sort(function(x,y){return x.min-y.min;});if(opt_totalRange&&opt_totalRange.min<inRanges[0].min){emptyRanges.push(tr.b.Range.fromExplicitRange(opt_totalRange.min,inRanges[0].min));}inRanges.forEach(function(range,index){for(var otherIndex=0;otherIndex<inRanges.length;++otherIndex){if(index===otherIndex)continue;var other=inRanges[otherIndex];if(other.min>range.max){emptyRanges.push(tr.b.Range.fromExplicitRange(range.max,other.min));return;}if(other.max>range.max){return;}}if(opt_totalRange&&range.max<opt_totalRange.max){emptyRanges.push(tr.b.Range.fromExplicitRange(range.max,opt_totalRange.max));}});return emptyRanges;}return{convertEventsToRanges:convertEventsToRanges,findEmptyRangesBetweenRanges:findEmptyRangesBetweenRanges,mergeRanges:mergeRanges};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/rect.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/rect.js

Statements: 11.54% (9 / 78)      Branches: 0% (0 / 7)      Functions: 4.55% (1 / 22)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./base.js");require("./math.js");'use strict';global.tr.exportTo('tr.b',function(){function Rect(){this.x=0;this.y=0;this.width=0;this.height=0;};Rect.fromXYWH=function(x,y,w,h){var rect=new Rect();rect.x=x;rect.y=y;rect.width=w;rect.height=h;return rect;};Rect.fromArray=function(ary){if(ary.length!=4)throw new Error('ary.length must be 4');var rect=new Rect();rect.x=ary[0];rect.y=ary[1];rect.width=ary[2];rect.height=ary[3];return rect;};Rect.prototype={__proto__:Object.prototype,get left(){return this.x;},get top(){return this.y;},get right(){return this.x+this.width;},get bottom(){return this.y+this.height;},toString:function(){return'Rect('+this.x+', '+this.y+', '+this.width+', '+this.height+')';},toArray:function(){return[this.x,this.y,this.width,this.height];},clone:function(){var rect=new Rect();rect.x=this.x;rect.y=this.y;rect.width=this.width;rect.height=this.height;return rect;},enlarge:function(pad){var rect=new Rect();this.enlargeFast(rect,pad);return rect;},enlargeFast:function(out,pad){out.x=this.x-pad;out.y=this.y-pad;out.width=this.width+2*pad;out.height=this.height+2*pad;return out;},size:function(){return{width:this.width,height:this.height};},scale:function(s){var rect=new Rect();this.scaleFast(rect,s);return rect;},scaleSize:function(s){return Rect.fromXYWH(this.x,this.y,this.width*s,this.height*s);},scaleFast:function(out,s){out.x=this.x*s;out.y=this.y*s;out.width=this.width*s;out.height=this.height*s;return out;},translate:function(v){var rect=new Rect();this.translateFast(rect,v);return rect;},translateFast:function(out,v){out.x=this.x+v[0];out.y=this.x+v[1];out.width=this.width;out.height=this.height;return out;},asUVRectInside:function(containingRect){var rect=new Rect();rect.x=(this.x-containingRect.x)/containingRect.width;rect.y=(this.y-containingRect.y)/containingRect.height;rect.width=this.width/containingRect.width;rect.height=this.height/containingRect.height;return rect;},intersects:function(that){var ok=true;ok&=this.x<that.right;ok&=this.right>that.x;ok&=this.y<that.bottom;ok&=this.bottom>that.y;return ok;},equalTo:function(rect){return rect&&this.x===rect.x&&this.y===rect.y&&this.width===rect.width&&this.height===rect.height;}};return{Rect:Rect};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/running_statistics.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/running_statistics.js

Statements: 6.86% (7 / 102)      Branches: 0% (0 / 48)      Functions: 11.76% (2 / 17)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){class RunningStatistics{constructor(){this.mean_=0;this.count_=0;this.max_=-Infinity;this.min_=Infinity;this.sum_=0;this.variance_=0;this.meanlogs_=0;}get count(){return this.count_;}get geometricMean(){if(this.meanlogs_===undefined)return 0;return Math.exp(this.meanlogs_);}get mean(){if(this.count_==0)return undefined;return this.mean_;}get max(){return this.max_;}get min(){return this.min_;}get sum(){return this.sum_;}get variance(){if(this.count_==0)return undefined;if(this.count_==1)return 0;return this.variance_/(this.count_-1);}get stddev(){if(this.count_==0)return undefined;return Math.sqrt(this.variance);}add(x){this.count_++;this.max_=Math.max(this.max_,x);this.min_=Math.min(this.min_,x);this.sum_+=x;if(x<=0)this.meanlogs_=undefined;else if(this.meanlogs_!==undefined)this.meanlogs_+=(Math.log(Math.abs(x))-this.meanlogs_)/this.count;if(this.count_===1){this.mean_=x;this.variance_=0;}else{var oldMean=this.mean_;var oldVariance=this.variance_;if(oldMean===Infinity||oldMean===-Infinity){this.mean_=this.sum_/this.count_;}else{this.mean_=oldMean+(x-oldMean)/this.count_;}this.variance_=oldVariance+(x-oldMean)*(x-this.mean_);}}merge(other){var result=new RunningStatistics();result.count_=this.count_+other.count_;result.sum_=this.sum_+other.sum_;result.min_=Math.min(this.min_,other.min_);result.max_=Math.max(this.max_,other.max_);if(result.count===0){result.mean_=0;result.variance_=0;result.meanlogs_=0;}else{result.mean_=result.sum/result.count;var deltaMean=(this.mean||0)-(other.mean||0);result.variance_=this.variance_+other.variance_+this.count*other.count*deltaMean*deltaMean/result.count;if(this.meanlogs_===undefined||other.meanlogs_===undefined){result.meanlogs_=undefined;}else{result.meanlogs_=(this.count*this.meanlogs_+other.count*other.meanlogs_)/result.count;}}return result;}asDict(){if(!this.count){return[];}return[this.count_,this.max_,this.meanlogs_,this.mean_,this.min_,this.sum_,this.variance_];}static fromDict(dict){var result=new RunningStatistics();if(dict.length!=7){return result;}var _dict=_slicedToArray(dict,7);result.count_=_dict[0];result.max_=_dict[1];result.meanlogs_=_dict[2];result.mean_=_dict[3];result.min_=_dict[4];result.sum_=_dict[5];result.variance_=_dict[6];return result;}}return{RunningStatistics:RunningStatistics};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/sinebow_color_generator.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/sinebow_color_generator.js

Statements: 93.48% (43 / 46)      Branches: 50% (4 / 8)      Functions: 100% (7 / 7)      Lines: 100% (1 / 1)      Ignored: none     

1 220  
"use strict";require("./color.js");require("./iteration_helpers.js");require("./math.js");'use strict';global.tr.exportTo('tr.b',function(){function SinebowColorGenerator(opt_a,opt_brightness){this.a_=opt_a===undefined?1:opt_a;this.brightness_=opt_brightness===undefined?1:opt_brightness;this.colorIndex_=0;this.keyToColor={};}SinebowColorGenerator.prototype={colorForKey:function(key){Eif(!this.keyToColor[key])this.keyToColor[key]=this.nextColor();return this.keyToColor[key];},nextColor:function(){var components=SinebowColorGenerator.nthColor(this.colorIndex_++);return tr.b.Color.fromString(SinebowColorGenerator.calculateColor(components[0],components[1],components[2],this.a_,this.brightness_));}};SinebowColorGenerator.PHI=(1+Math.sqrt(5))/2;SinebowColorGenerator.sinebow_=function(h){h+=0.5;h=-h;var r=Math.sin(Math.PI*h);var g=Math.sin(Math.PI*(h+1/3));var b=Math.sin(Math.PI*(h+2/3));r*=r;g*=g;b*=b;var y=2*(0.2989*r+0.5870*g+0.1140*b);r/=y;g/=y;b/=y;return[256*r,256*g,256*b];};SinebowColorGenerator.nthColor=function(n){return SinebowColorGenerator.sinebow_(n*this.PHI);};SinebowColorGenerator.calculateColor=function(r,g,b,a,brightness){Eif(brightness<=1){r*=brightness;g*=brightness;b*=brightness;}else{r=tr.b.lerp(tr.b.normalize(brightness,1,2),r,255);g=tr.b.lerp(tr.b.normalize(brightness,1,2),g,255);b=tr.b.lerp(tr.b.normalize(brightness,1,2),b,255);}r=Math.round(r);g=Math.round(g);b=Math.round(b);return'rgba('+r+','+g+','+b+', '+a+')';};return{SinebowColorGenerator:SinebowColorGenerator};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/sorted_array_utils.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/sorted_array_utils.js

Statements: 10% (12 / 120)      Branches: 0% (0 / 98)      Functions: 10% (1 / 10)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function findLowIndexInSortedArray(ary,mapFn,loVal){if(ary.length==0)return 1;var low=0;var high=ary.length-1;var i,comparison;var hitPos=-1;while(low<=high){i=Math.floor((low+high)/2);comparison=mapFn(ary[i])-loVal;if(comparison<0){low=i+1;continue;}else if(comparison>0){high=i-1;continue;}else{hitPos=i;high=i-1;}}return hitPos!=-1?hitPos:low;}function findHighIndexInSortedArray(ary,mapFn,loVal,hiVal){var lo=loVal||0;var hi=hiVal!==undefined?hiVal:ary.length;while(lo<hi){var mid=lo+hi>>1;if(mapFn(ary[mid])>=0)lo=mid+1;else hi=mid;}return hi;}function findIndexInSortedIntervals(ary,mapLoFn,mapWidthFn,loVal){var first=findLowIndexInSortedArray(ary,mapLoFn,loVal);if(first==0){if(loVal>=mapLoFn(ary[0])&&loVal<mapLoFn(ary[0])+mapWidthFn(ary[0],0)){return 0;}else{return-1;}}else if(first<ary.length){if(loVal>=mapLoFn(ary[first])&&loVal<mapLoFn(ary[first])+mapWidthFn(ary[first],first)){return first;}else if(loVal>=mapLoFn(ary[first-1])&&loVal<mapLoFn(ary[first-1])+mapWidthFn(ary[first-1],first-1)){return first-1;}else{return ary.length;}}else if(first==ary.length){if(loVal>=mapLoFn(ary[first-1])&&loVal<mapLoFn(ary[first-1])+mapWidthFn(ary[first-1],first-1)){return first-1;}else{return ary.length;}}else{return ary.length;}}function findIndexInSortedClosedIntervals(ary,mapLoFn,mapHiFn,val){var i=findLowIndexInSortedArray(ary,mapLoFn,val);if(i===0){if(val>=mapLoFn(ary[0],0)&&val<=mapHiFn(ary[0],0)){return 0;}else{return-1;}}else if(i<ary.length){if(val>=mapLoFn(ary[i-1],i-1)&&val<=mapHiFn(ary[i-1],i-1)){return i-1;}else if(val>=mapLoFn(ary[i],i)&&val<=mapHiFn(ary[i],i)){return i;}else{return ary.length;}}else if(i==ary.length){if(val>=mapLoFn(ary[i-1],i-1)&&val<=mapHiFn(ary[i-1],i-1)){return i-1;}else{return ary.length;}}else{return ary.length;}}function iterateOverIntersectingIntervals(ary,mapLoFn,mapWidthFn,loVal,hiVal,cb){if(ary.length==0)return;if(loVal>hiVal)return;var i=findLowIndexInSortedArray(ary,mapLoFn,loVal);if(i==-1){return;}if(i>0){var hi=mapLoFn(ary[i-1])+mapWidthFn(ary[i-1],i-1);if(hi>=loVal){cb(ary[i-1],i-1);}}if(i==ary.length){return;}for(var n=ary.length;i<n;i++){var lo=mapLoFn(ary[i]);if(lo>=hiVal)break;cb(ary[i],i);}}function getIntersectingIntervals(ary,mapLoFn,mapWidthFn,loVal,hiVal){var tmp=[];iterateOverIntersectingIntervals(ary,mapLoFn,mapWidthFn,loVal,hiVal,function(d){tmp.push(d);});return tmp;}function findClosestElementInSortedArray(ary,mapFn,val,maxDiff){if(ary.length===0)return null;var aftIdx=findLowIndexInSortedArray(ary,mapFn,val);var befIdx=aftIdx>0?aftIdx-1:0;if(aftIdx===ary.length)aftIdx-=1;var befDiff=Math.abs(val-mapFn(ary[befIdx]));var aftDiff=Math.abs(val-mapFn(ary[aftIdx]));if(befDiff>maxDiff&&aftDiff>maxDiff)return null;var idx=befDiff<aftDiff?befIdx:aftIdx;return ary[idx];}function findClosestIntervalInSortedIntervals(ary,mapLoFn,mapHiFn,val,maxDiff){if(ary.length===0)return null;var idx=findLowIndexInSortedArray(ary,mapLoFn,val);if(idx>0)idx-=1;var hiInt=ary[idx];var loInt=hiInt;if(val>mapHiFn(hiInt)&&idx+1<ary.length)loInt=ary[idx+1];var loDiff=Math.abs(val-mapLoFn(loInt));var hiDiff=Math.abs(val-mapHiFn(hiInt));if(loDiff>maxDiff&&hiDiff>maxDiff)return null;if(loDiff<hiDiff)return loInt;else return hiInt;}return{findLowIndexInSortedArray:findLowIndexInSortedArray,findHighIndexInSortedArray:findHighIndexInSortedArray,findIndexInSortedIntervals:findIndexInSortedIntervals,findIndexInSortedClosedIntervals:findIndexInSortedClosedIntervals,iterateOverIntersectingIntervals:iterateOverIntersectingIntervals,getIntersectingIntervals:getIntersectingIntervals,findClosestElementInSortedArray:findClosestElementInSortedArray,findClosestIntervalInSortedIntervals:findClosestIntervalInSortedIntervals};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/statistics.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/statistics.js

Statements: 17.35% (51 / 294)      Branches: 4.26% (4 / 94)      Functions: 8.33% (5 / 60)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./math.js");require("./range.js");'use strict';(function(){Eif(tr.isNode){var mwuAbsPath=HTMLImportsLoader.hrefToAbsolutePath('/mannwhitneyu.js');var mwuModule=require(mwuAbsPath);for(var exportName in mwuModule){global[exportName]=mwuModule[exportName];}}})(this);'use strict';global.tr.exportTo('tr.b',function(){var identity=x=>x;var Statistics={};Statistics.divideIfPossibleOrZero=function(numerator,denominator){if(denominator===0)return 0;return numerator/denominator;};Statistics.sum=function(ary,opt_func,opt_this){var func=opt_func||identity;var ret=0;var i=0;for(var elt of ary)ret+=func.call(opt_this,elt,i++);return ret;};Statistics.mean=function(ary,opt_func,opt_this){var func=opt_func||identity;var sum=0;var i=0;for(var elt of ary)sum+=func.call(opt_this,elt,i++);if(i===0)return undefined;return sum/i;};Statistics.geometricMean=function(ary,opt_func,opt_this){var func=opt_func||identity;var i=0;var logsum=0;for(var elt of ary){var x=func.call(opt_this,elt,i++);if(x<=0)return 0;logsum+=Math.log(Math.abs(x));}if(i===0)return 1;return Math.exp(logsum/i);};Statistics.weightedMean=function(ary,weightCallback,opt_valueCallback,opt_this){var valueCallback=opt_valueCallback||identity;var numerator=0;var denominator=0;var i=-1;for(var elt of ary){i++;var value=valueCallback.call(opt_this,elt,i);if(value===undefined)continue;var weight=weightCallback.call(opt_this,elt,i,value);numerator+=weight*value;denominator+=weight;}if(denominator===0)return undefined;return numerator/denominator;};Statistics.variance=function(ary,opt_func,opt_this){if(ary.length===0)return undefined;if(ary.length===1)return 0;var func=opt_func||identity;var mean=Statistics.mean(ary,func,opt_this);var sumOfSquaredDistances=Statistics.sum(ary,function(d,i){var v=func.call(this,d,i)-mean;return v*v;},opt_this);return sumOfSquaredDistances/(ary.length-1);};Statistics.stddev=function(ary,opt_func,opt_this){if(ary.length==0)return undefined;return Math.sqrt(Statistics.variance(ary,opt_func,opt_this));};Statistics.max=function(ary,opt_func,opt_this){var func=opt_func||identity;var ret=-Infinity;var i=0;for(var elt of ary)ret=Math.max(ret,func.call(opt_this,elt,i++));return ret;};Statistics.min=function(ary,opt_func,opt_this){var func=opt_func||identity;var ret=Infinity;var i=0;for(var elt of ary)ret=Math.min(ret,func.call(opt_this,elt,i++));return ret;};Statistics.range=function(ary,opt_func,opt_this){var func=opt_func||identity;var ret=new tr.b.Range();var i=0;for(var elt of ary)ret.addValue(func.call(opt_this,elt,i++));return ret;};Statistics.percentile=function(ary,percent,opt_func,opt_this){if(!(percent>=0&&percent<=1))throw new Error('percent must be [0,1]');var func=opt_func||identity;var tmp=new Array(ary.length);var i=0;for(var elt of ary)tmp[i]=func.call(opt_this,elt,i++);tmp.sort((a,b)=>a-b);var idx=Math.floor((ary.length-1)*percent);return tmp[idx];};Statistics.normalizeSamples=function(samples){if(samples.length===0){return{normalized_samples:samples,scale:1.0};}samples=samples.slice().sort(function(a,b){return a-b;});var low=Math.min.apply(null,samples);var high=Math.max.apply(null,samples);var newLow=0.5/samples.length;var newHigh=(samples.length-0.5)/samples.length;if(high-low===0.0){samples=Array.apply(null,new Array(samples.length)).map(function(){return 0.5;});return{normalized_samples:samples,scale:1.0};}var scale=(newHigh-newLow)/(high-low);for(var i=0;i<samples.length;i++){samples[i]=(samples[i]-low)*scale+newLow;}return{normalized_samples:samples,scale:scale};};Statistics.discrepancy=function(samples,opt_locationCount){if(samples.length===0)return 0.0;var maxLocalDiscrepancy=0;var invSampleCount=1.0/samples.length;var locations=[];var countLess=[];var countLessEqual=[];if(opt_locationCount!==undefined){var sampleIndex=0;for(var i=0;i<opt_locationCount;i++){var location=i/(opt_locationCount-1);locations.push(location);while(sampleIndex<samples.length&&samples[sampleIndex]<location){sampleIndex+=1;}countLess.push(sampleIndex);while(sampleIndex<samples.length&&samples[sampleIndex]<=location){sampleIndex+=1;}countLessEqual.push(sampleIndex);}}else{if(samples[0]>0.0){locations.push(0.0);countLess.push(0);countLessEqual.push(0);}for(var i=0;i<samples.length;i++){locations.push(samples[i]);countLess.push(i);countLessEqual.push(i+1);}if(samples[-1]<1.0){locations.push(1.0);countLess.push(samples.length);countLessEqual.push(samples.length);}}var maxDiff=0;var minDiff=0;for(var i=1;i<locations.length;i++){var length=locations[i]-locations[i-1];var countClosed=countLessEqual[i]-countLess[i-1];var countOpen=countLess[i]-countLessEqual[i-1];var countClosedIncrement=countLessEqual[i]-countLessEqual[i-1];var countOpenIncrement=countLess[i]-countLess[i-1];maxDiff=Math.max(countClosedIncrement*invSampleCount-length+maxDiff,countClosed*invSampleCount-length);minDiff=Math.min(countOpenIncrement*invSampleCount-length+minDiff,countOpen*invSampleCount-length);maxLocalDiscrepancy=Math.max(maxDiff,-minDiff,maxLocalDiscrepancy);}return maxLocalDiscrepancy;};Statistics.timestampsDiscrepancy=function(timestamps,opt_absolute,opt_locationCount){if(timestamps.length===0)return 0.0;if(opt_absolute===undefined)opt_absolute=true;if(Array.isArray(timestamps[0])){var rangeDiscrepancies=timestamps.map(function(r){return Statistics.timestampsDiscrepancy(r);});return Math.max.apply(null,rangeDiscrepancies);}var s=Statistics.normalizeSamples(timestamps);var samples=s.normalized_samples;var sampleScale=s.scale;var discrepancy=Statistics.discrepancy(samples,opt_locationCount);var invSampleCount=1.0/samples.length;if(opt_absolute===true){discrepancy/=sampleScale;}else{discrepancy=tr.b.clamp((discrepancy-invSampleCount)/(1.0-invSampleCount),0.0,1.0);}return discrepancy;};Statistics.durationsDiscrepancy=function(durations,opt_absolute,opt_locationCount){if(durations.length===0)return 0.0;var timestamps=durations.reduce(function(prev,curr,index,array){prev.push(prev[prev.length-1]+curr);return prev;},[0]);return Statistics.timestampsDiscrepancy(timestamps,opt_absolute,opt_locationCount);};Statistics.uniformlySampleArray=function(samples,count){if(samples.length<=count){return samples;}while(samples.length>count){var i=parseInt(Math.random()*samples.length);samples.splice(i,1);}return samples;};Statistics.uniformlySampleStream=function(samples,streamLength,newElement,numSamples){if(streamLength<=numSamples){if(samples.length>=streamLength)samples[streamLength-1]=newElement;else samples.push(newElement);return;}var probToKeep=numSamples/streamLength;if(Math.random()>probToKeep)return;var index=Math.floor(Math.random()*numSamples);samples[index]=newElement;};Statistics.mergeSampledStreams=function(samplesA,streamLengthA,samplesB,streamLengthB,numSamples){if(streamLengthB<numSamples){var nbElements=Math.min(streamLengthB,samplesB.length);for(var i=0;i<nbElements;++i){Statistics.uniformlySampleStream(samplesA,streamLengthA+i+1,samplesB[i],numSamples);}return;}if(streamLengthA<numSamples){var nbElements=Math.min(streamLengthA,samplesA.length);var tempSamples=samplesB.slice();for(var i=0;i<nbElements;++i){Statistics.uniformlySampleStream(tempSamples,streamLengthB+i+1,samplesA[i],numSamples);}for(var i=0;i<tempSamples.length;++i){samplesA[i]=tempSamples[i];}return;}var nbElements=Math.min(numSamples,samplesB.length);var probOfSwapping=streamLengthB/(streamLengthA+streamLengthB);for(var i=0;i<nbElements;++i){if(Math.random()<probOfSwapping){samplesA[i]=samplesB[i];}}};function Distribution(){}Distribution.prototype={computeDensity:function(x){throw Error('Not implemented');},computePercentile:function(x){throw Error('Not implemented');},computeComplementaryPercentile:function(x){return 1-this.computePercentile(x);},get mean(){throw Error('Not implemented');},get mode(){throw Error('Not implemented');},get median(){throw Error('Not implemented');},get standardDeviation(){throw Error('Not implemented');},get variance(){throw Error('Not implemented');}};Statistics.UniformDistribution=function(opt_range){if(!opt_range)opt_range=tr.b.Range.fromExplicitRange(0,1);this.range=opt_range;};Statistics.UniformDistribution.prototype={__proto__:Distribution.prototype,computeDensity:function(x){return 1/this.range.range;},computePercentile:function(x){return tr.b.normalize(x,this.range.min,this.range.max);},get mean(){return this.range.center;},get mode(){return undefined;},get median(){return this.mean;},get standardDeviation(){return Math.sqrt(this.variance);},get variance(){return Math.pow(this.range.range,2)/12;}};Statistics.NormalDistribution=function(opt_mean,opt_variance){this.mean_=opt_mean||0;this.variance_=opt_variance||1;this.standardDeviation_=Math.sqrt(this.variance_);};Statistics.NormalDistribution.prototype={__proto__:Distribution.prototype,computeDensity:function(x){var scale=1.0/(this.standardDeviation*Math.sqrt(2.0*Math.PI));var exponent=-Math.pow(x-this.mean,2)/(2.0*this.variance);return scale*Math.exp(exponent);},computePercentile:function(x){var standardizedX=(x-this.mean)/Math.sqrt(2.0*this.variance);return(1.0+tr.b.erf(standardizedX))/2.0;},get mean(){return this.mean_;},get median(){return this.mean;},get mode(){return this.mean;},get standardDeviation(){return this.standardDeviation_;},get variance(){return this.variance_;}};Statistics.LogNormalDistribution=function(opt_location,opt_shape){this.normalDistribution_=new Statistics.NormalDistribution(opt_location,Math.pow(opt_shape||1,2));};Statistics.LogNormalDistribution.prototype={__proto__:Statistics.NormalDistribution.prototype,computeDensity:function(x){return this.normalDistribution_.computeDensity(Math.log(x))/x;},computePercentile:function(x){return this.normalDistribution_.computePercentile(Math.log(x));},get mean(){return Math.exp(this.normalDistribution_.mean+this.normalDistribution_.variance/2);},get variance(){var nm=this.normalDistribution_.mean;var nv=this.normalDistribution_.variance;return Math.exp(2*(nm+nv))-Math.exp(2*nm+nv);},get standardDeviation(){return Math.sqrt(this.variance);},get median(){return Math.exp(this.normalDistribution_.mean);},get mode(){return Math.exp(this.normalDistribution_.mean-this.normalDistribution_.variance);}};Statistics.LogNormalDistribution.fromMedianAndDiminishingReturns=function(median,diminishingReturns){diminishingReturns=Math.log(diminishingReturns/median);var shape=Math.sqrt(1-3*diminishingReturns-Math.sqrt(Math.pow(diminishingReturns-3,2)-8))/2;var location=Math.log(median);return new Statistics.LogNormalDistribution(location,shape);};Statistics.DEFAULT_ALPHA=0.05;Statistics.Significance={INSIGNIFICANT:-1,DONT_CARE:0,SIGNIFICANT:1};Statistics.mwu=function(a,b,opt_alpha){var result=mannwhitneyu.test(a,b);var alpha=opt_alpha||Statistics.DEFAULT_ALPHA;result.significance=result.p<alpha?Statistics.Significance.SIGNIFICANT:Statistics.Significance.INSIGNIFICANT;return result;};return{Statistics:Statistics};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/task.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/task.js

Statements: 15.28% (11 / 72)      Branches: 0% (0 / 22)      Functions: 6.67% (1 / 15)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./raf.js");require("./timing.js");'use strict';global.tr.exportTo('tr.b',function(){var Timing=tr.b.Timing;function Task(runCb,thisArg){if(runCb!==undefined&&thisArg===undefined)throw new Error('Almost certainly, you meant to pass a thisArg.');this.runCb_=runCb;this.thisArg_=thisArg;this.afterTask_=undefined;this.subTasks_=[];}Task.prototype={get name(){return this.runCb_.name;},subTask:function(cb,thisArg){if(cb instanceof Task)this.subTasks_.push(cb);else this.subTasks_.push(new Task(cb,thisArg));return this.subTasks_[this.subTasks_.length-1];},run:function(){if(this.runCb_!==undefined)this.runCb_.call(this.thisArg_,this);var subTasks=this.subTasks_;this.subTasks_=undefined;if(!subTasks.length)return this.afterTask_;for(var i=1;i<subTasks.length;i++)subTasks[i-1].afterTask_=subTasks[i];subTasks[subTasks.length-1].afterTask_=this.afterTask_;return subTasks[0];},after:function(cb,thisArg){if(this.afterTask_)throw new Error('Has an after task already');if(cb instanceof Task)this.afterTask_=cb;else this.afterTask_=new Task(cb,thisArg);return this.afterTask_;},timedAfter:function(groupName,cb,thisArg,opt_args){if(cb.name==='')throw new Error('Anonymous Task is not allowed');return this.namedTimedAfter(groupName,cb.name,cb,thisArg,opt_args);},namedTimedAfter:function(groupName,name,cb,thisArg,opt_args){if(this.afterTask_)throw new Error('Has an after task already');var realTask;if(cb instanceof Task)realTask=cb;else realTask=new Task(cb,thisArg);this.afterTask_=new Task(function(task){var markedTask=Timing.mark(groupName,name,opt_args);task.subTask(realTask,thisArg);task.subTask(function(){markedTask.end();},thisArg);},thisArg);return this.afterTask_;},enqueue:function(cb,thisArg){var lastTask=this;while(lastTask.afterTask_)lastTask=lastTask.afterTask_;return lastTask.after(cb,thisArg);}};Task.RunSynchronously=function(task){var curTask=task;while(curTask)curTask=curTask.run();};Task.RunWhenIdle=function(task){return new Promise(function(resolve,reject){var curTask=task;function runAnother(){try{curTask=curTask.run();}catch(e){reject(e);console.error(e.stack);return;}if(curTask){tr.b.requestIdleCallback(runAnother);return;}resolve();}tr.b.requestIdleCallback(runAnother);});};return{Task:Task};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/time_display_modes.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/time_display_modes.js

Statements: 77.78% (7 / 9)      Branches: 100% (0 / 0)      Functions: 33.33% (1 / 3)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./unit_scale.js");'use strict';global.tr.exportTo('tr.b',function(){var msDisplayMode={scale:1e-3,suffix:'ms',roundedLess:function(a,b){return Math.round(a*1000)<Math.round(b*1000);},formatSpec:{unit:'s',unitPrefix:tr.b.UnitScale.Metric.MILLI,minimumFractionDigits:3}};var nsDisplayMode={scale:1e-9,suffix:'ns',roundedLess:function(a,b){return Math.round(a*1000000)<Math.round(b*1000000);},formatSpec:{unit:'s',unitPrefix:tr.b.UnitScale.Metric.NANO,maximumFractionDigits:0}};var TimeDisplayModes={ns:nsDisplayMode,ms:msDisplayMode};return{TimeDisplayModes:TimeDisplayModes};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/timing.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/timing.js

Statements: 28% (14 / 50)      Branches: 0% (0 / 12)      Functions: 8.33% (1 / 12)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./base.js");require("./base64.js");'use strict';global.tr.exportTo('tr.b',function(){var Base64=tr.b.Base64;function computeUserTimingMarkName(groupName,functionName,opt_args){if(groupName===undefined)throw new Error('getMeasureString should have group name');if(functionName===undefined)throw new Error('getMeasureString should have function name');var userTimingMarkName=groupName+':'+functionName;if(opt_args!==undefined){userTimingMarkName+='/';userTimingMarkName+=Base64.btoa(JSON.stringify(opt_args));}return userTimingMarkName;}function Timing(){}Timing.nextMarkNumber=0;Timing.mark=function(groupName,functionName,opt_args){if(tr.isHeadless){return{end:function(){}};}var userTimingMarkName=computeUserTimingMarkName(groupName,functionName,opt_args);var markBeginName='tvcm.mark'+Timing.nextMarkNumber++;var markEndName='tvcm.mark'+Timing.nextMarkNumber++;window.performance.mark(markBeginName);return{end:function(){window.performance.mark(markEndName);window.performance.measure(userTimingMarkName,markBeginName,markEndName);}};};Timing.wrap=function(groupName,callback,opt_args){if(groupName===undefined)throw new Error('Timing.wrap should have group name');if(callback.name==='')throw new Error('Anonymous function is not allowed');return Timing.wrapNamedFunction(groupName,callback.name,callback,opt_args);};Timing.wrapNamedFunction=function(groupName,functionName,callback,opt_args){function timedNamedFunction(){var markedTime=Timing.mark(groupName,functionName,opt_args);try{callback.apply(this,arguments);}finally{markedTime.end();}}return timedNamedFunction;};function TimedNamedPromise(groupName,name,executor,opt_args){var markedTime=Timing.mark(groupName,name,opt_args);var promise=new Promise(executor);promise.then(function(result){markedTime.end();return result;},function(e){markedTime.end();throw e;});return promise;}return{_computeUserTimingMarkName:computeUserTimingMarkName,TimedNamedPromise:TimedNamedPromise,Timing:Timing};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/unit.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/unit.js

Statements: 48.03% (73 / 152)      Branches: 14.29% (10 / 70)      Functions: 40% (8 / 20)      Lines: 100% (1 / 1)      Ignored: none     

1 254  
"use strict";require("./event.js");require("./event_target.js");require("./iteration_helpers.js");require("./time_display_modes.js");require("./unit_scale.js");'use strict';global.tr.exportTo('tr.b',function(){var TimeDisplayModes=tr.b.TimeDisplayModes;var PLUS_MINUS_SIGN=String.fromCharCode(177);function max(a,b){if(a===undefined)return b;if(b===undefined)return a;return a.scale>b.scale?a:b;}var ImprovementDirection={DONT_CARE:0,BIGGER_IS_BETTER:1,SMALLER_IS_BETTER:2};function Unit(unitName,jsonName,basePrefix,isDelta,improvementDirection,formatSpec){this.unitName=unitName;this.jsonName=jsonName;this.basePrefix=basePrefix;this.isDelta=isDelta;this.improvementDirection=improvementDirection;this.formatSpec_=formatSpec;this.baseUnit=undefined;this.correspondingDeltaUnit=undefined;}Unit.prototype={asJSON:function(){return this.jsonName;},get unitString(){var formatSpec=this.formatSpec_;if(typeof formatSpec==='function')formatSpec=formatSpec();if(!formatSpec.unit){return'';}var unitString='';var unitPrefix=formatSpec.unitPrefix;if(unitPrefix!==undefined){var selectedPrefix;if(unitPrefix instanceof Array){selectedPrefix=unitPrefix[0];}else{selectedPrefix=unitPrefix;}unitString+=selectedPrefix.symbol||'';}unitString+=formatSpec.unit;return unitString;},format:function(value,opt_context){var context=opt_context||{};var formatSpec=this.formatSpec_;if(typeof formatSpec==='function')formatSpec=formatSpec();function resolveProperty(propertyName){if(propertyName in context)return context[propertyName];else if(propertyName in formatSpec)return formatSpec[propertyName];else return undefined;}var signString='';if(value<0){signString='-';value=-value;}else if(this.isDelta){signString=value===0?PLUS_MINUS_SIGN:'+';}var unitString='';if(formatSpec.unit){if(formatSpec.unitHasPrecedingSpace!==false)unitString+=' ';var unitPrefix=resolveProperty('unitPrefix');if(unitPrefix!==undefined){var selectedPrefix;if(unitPrefix instanceof Array){var i=0;while(i<unitPrefix.length-1&&value/unitPrefix[i+1].value>=1){i++;}selectedPrefix=unitPrefix[i];}else{selectedPrefix=unitPrefix;}unitString+=selectedPrefix.symbol||'';value=tr.b.convertUnit(value,this.basePrefix,selectedPrefix);}else{value=tr.b.convertUnit(value,this.basePrefix,tr.b.UnitScale.Metric.NONE);}unitString+=formatSpec.unit;}var minimumFractionDigits=resolveProperty('minimumFractionDigits');var maximumFractionDigits=resolveProperty('maximumFractionDigits');if(minimumFractionDigits>maximumFractionDigits){if('minimumFractionDigits'in context&&!('maximumFractionDigits'in context)){maximumFractionDigits=minimumFractionDigits;}else if('maximumFractionDigits'in context&&!('minimumFractionDigits'in context)){minimumFractionDigits=maximumFractionDigits;}}var numberString=value.toLocaleString(undefined,{minimumFractionDigits:minimumFractionDigits,maximumFractionDigits:maximumFractionDigits});return signString+numberString+unitString;}};Unit.reset=function(){Unit.currentTimeDisplayMode=TimeDisplayModes.ms;};Unit.timestampFromUs=function(us){return tr.b.convertUnit(us,tr.b.UnitScale.Metric.MICRO,tr.b.UnitScale.Metric.MILLI);};Object.defineProperty(Unit,'currentTimeDisplayMode',{get:function(){return Unit.currentTimeDisplayMode_;},set:function(value){Iif(Unit.currentTimeDisplayMode_===value)return;Unit.currentTimeDisplayMode_=value;Unit.dispatchEvent(new tr.b.Event('display-mode-changed'));}});Unit.didPreferredTimeDisplayUnitChange=function(){var largest=undefined;var els=tr.b.findDeepElementsMatching(document.body,'tr-v-ui-preferred-display-unit');els.forEach(function(el){largest=max(largest,el.preferredTimeDisplayMode);});Unit.currentDisplayUnit=largest===undefined?TimeDisplayModes.ms:largest;};Unit.byName={};Unit.byJSONName={};Unit.fromJSON=function(object){var u=Unit.byJSONName[object];if(u){return u;}throw new Error('Unrecognized unit');};Unit.define=function(params){var definedUnits=[];tr.b.iterItems(ImprovementDirection,function(_,improvementDirection){var regularUnit=Unit.defineUnitVariant_(params,false,improvementDirection);var deltaUnit=Unit.defineUnitVariant_(params,true,improvementDirection);regularUnit.correspondingDeltaUnit=deltaUnit;deltaUnit.correspondingDeltaUnit=deltaUnit;definedUnits.push(regularUnit,deltaUnit);});var baseUnit=Unit.byName[params.baseUnitName];definedUnits.forEach(u=>u.baseUnit=baseUnit);};Unit.nameSuffixForImprovementDirection=function(improvementDirection){switch(improvementDirection){case ImprovementDirection.DONT_CARE:return'';case ImprovementDirection.BIGGER_IS_BETTER:return'_biggerIsBetter';case ImprovementDirection.SMALLER_IS_BETTER:return'_smallerIsBetter';default:throw new Error('Unknown improvement direction: '+improvementDirection);}};Unit.defineUnitVariant_=function(params,isDelta,improvementDirection){var nameSuffix=isDelta?'Delta':'';nameSuffix+=Unit.nameSuffixForImprovementDirection(improvementDirection);var unitName=params.baseUnitName+nameSuffix;var jsonName=params.baseJsonName+nameSuffix;Iif(Unit.byName[unitName]!==undefined)throw new Error('Unit \''+unitName+'\' already exists');Iif(Unit.byJSONName[jsonName]!==undefined)throw new Error('JSON unit \''+jsonName+'\' alread exists');var basePrefix=params.basePrefix?params.basePrefix:tr.b.UnitScale.Metric.NONE;var unit=new Unit(unitName,jsonName,basePrefix,isDelta,improvementDirection,params.formatSpec);Unit.byName[unitName]=unit;Unit.byJSONName[jsonName]=unit;return unit;};tr.b.EventTarget.decorate(Unit);Unit.reset();Unit.define({baseUnitName:'timeDurationInMs',baseJsonName:'ms',basePrefix:tr.b.UnitScale.Metric.MILLI,formatSpec:function(){return Unit.currentTimeDisplayMode_.formatSpec;}});Unit.define({baseUnitName:'timeStampInMs',baseJsonName:'tsMs',basePrefix:tr.b.UnitScale.Metric.MILLI,formatSpec:function(){return Unit.currentTimeDisplayMode_.formatSpec;}});Unit.define({baseUnitName:'normalizedPercentage',baseJsonName:'n%',formatSpec:{unit:'%',unitPrefix:{value:0.01},unitHasPrecedingSpace:false,minimumFractionDigits:3,maximumFractionDigits:3}});Unit.define({baseUnitName:'sizeInBytes',baseJsonName:'sizeInBytes',formatSpec:{unit:'B',unitPrefix:tr.b.UnitScale.Binary.AUTO,minimumFractionDigits:1,maximumFractionDigits:1}});Unit.define({baseUnitName:'energyInJoules',baseJsonName:'J',formatSpec:{unit:'J',minimumFractionDigits:3}});Unit.define({baseUnitName:'powerInWatts',baseJsonName:'W',formatSpec:{unit:'W',minimumFractionDigits:3}});Unit.define({baseUnitName:'unitlessNumber',baseJsonName:'unitless',formatSpec:{minimumFractionDigits:3,maximumFractionDigits:3}});Unit.define({baseUnitName:'count',baseJsonName:'count',formatSpec:{minimumFractionDigits:0,maximumFractionDigits:0}});Unit.define({baseUnitName:'sigma',baseJsonName:'sigma',formatSpec:{unit:String.fromCharCode(963),minimumFractionDigits:1,maximumFractionDigits:1}});return{ImprovementDirection:ImprovementDirection,Unit:Unit};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/unit_scale.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/unit_scale.js

Statements: 85.71% (18 / 21)      Branches: 50% (3 / 6)      Functions: 100% (3 / 3)      Lines: 100% (1 / 1)      Ignored: none     

1 210  
"use strict";require("./iteration_helpers.js");'use strict';var GREEK_SMALL_LETTER_MU=String.fromCharCode(956);global.tr.exportTo('tr.b',function(){var UnitScale={};function defineUnitScale(name,prefixes){Iif(UnitScale[name]!==undefined)throw new Error('Unit scale \''+name+'\' already exists');Iif(prefixes.AUTO!==undefined){throw new Error('\'AUTO\' unit prefix will be added automatically '+'for unit scale \''+name+'\'');}prefixes.AUTO=tr.b.dictionaryValues(prefixes);prefixes.AUTO.sort((a,b)=>a.value-b.value);UnitScale[name]=prefixes;}function convertUnit(value,fromPrefix,toPrefix){Iif(value===undefined)return undefined;return value*(fromPrefix.value/toPrefix.value);}defineUnitScale('Binary',{NONE:{value:Math.pow(1024,0),symbol:''},KIBI:{value:Math.pow(1024,1),symbol:'Ki'},MEBI:{value:Math.pow(1024,2),symbol:'Mi'},GIBI:{value:Math.pow(1024,3),symbol:'Gi'},TEBI:{value:Math.pow(1024,4),symbol:'Ti'}});defineUnitScale('Metric',{NANO:{value:1e-9,symbol:'n'},MICRO:{value:1e-6,symbol:GREEK_SMALL_LETTER_MU},MILLI:{value:1e-3,symbol:'m'},NONE:{value:1,symbol:''},KILO:{value:1e3,symbol:'k'},MEGA:{value:1e6,symbol:'M'},GIGA:{value:1e9,symbol:'G'}});return{UnitScale:UnitScale,convertUnit:convertUnit};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/utils.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/base/utils.js

Statements: 17.46% (11 / 63)      Branches: 0% (0 / 40)      Functions: 11.11% (1 / 9)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./base.js");'use strict';global.tr.exportTo('tr.b',function(){function addSingletonGetter(ctor){ctor.getInstance=function(){return ctor.instance_||(ctor.instance_=new ctor());};}function deepCopy(value){if(!(value instanceof Object)){if(value===undefined||value===null)return value;if(typeof value=='string')return value.substring();if(typeof value=='boolean')return value;if(typeof value=='number')return value;throw new Error('Unrecognized: '+typeof value);}var object=value;if(object instanceof Array){var res=new Array(object.length);for(var i=0;i<object.length;i++)res[i]=deepCopy(object[i]);return res;}if(object.__proto__!=Object.prototype)throw new Error('Can only clone simple types');var res={};for(var key in object){res[key]=deepCopy(object[key]);}return res;}function normalizeException(e){if(e===undefined||e===null){return{typeName:'UndefinedError',message:'Unknown: null or undefined exception',stack:'Unknown'};}if(typeof e=='string'){return{typeName:'StringError',message:e,stack:[e]};}var typeName;if(e.name){typeName=e.name;}else if(e.constructor){if(e.constructor.name){typeName=e.constructor.name;}else{typeName='AnonymousError';}}else{typeName='ErrorWithNoConstructor';}var msg=e.message?e.message:'Unknown';return{typeName:typeName,message:msg,stack:e.stack?e.stack:[msg]};}function stackTraceAsString(){return new Error().stack+'';}function stackTrace(){var stack=stackTraceAsString();stack=stack.split('\n');return stack.slice(2);}function getUsingPath(path,fromDict){var parts=path.split('.');var cur=fromDict;for(var part;parts.length&&(part=parts.shift());){if(!parts.length){return cur[part];}else if(part in cur){cur=cur[part];}else{return undefined;}}return undefined;}function formatDate(date){return date.toISOString().replace('T',' ').slice(0,19);}return{addSingletonGetter:addSingletonGetter,deepCopy:deepCopy,normalizeException:normalizeException,stackTrace:stackTrace,stackTraceAsString:stackTraceAsString,formatDate:formatDate,getUsingPath:getUsingPath};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/core/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/core/

Statements: 40.68% (24 / 59)      Branches: 0% (0 / 19)      Functions: 9.52% (2 / 21)      Lines: 100% (2 / 2)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/core/
File Statements Branches Functions Lines
auditor.js 84.62% (11 / 13) 100% (0 / 0) 16.67% (1 / 6) 100% (1 / 1)
filter.js 28.26% (13 / 46) 0% (0 / 19) 6.67% (1 / 15) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/core/auditor.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/core/auditor.js

Statements: 84.62% (11 / 13)      Branches: 100% (0 / 0)      Functions: 16.67% (1 / 6)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");require("../base/extension_registry.js");'use strict';global.tr.exportTo('tr.c',function(){function Auditor(model){this.model_=model;}Auditor.prototype={__proto__:Object.prototype,get model(){return this.model_;},runAnnotate:function(){},installUserFriendlyCategoryDriverIfNeeded:function(){},runAudit:function(){}};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.defaultMetadata={};options.mandatoryBaseClass=Auditor;tr.b.decorateExtensionRegistry(Auditor,options);return{Auditor:Auditor};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/core/filter.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/core/filter.js

Statements: 28.26% (13 / 46)      Branches: 0% (0 / 19)      Functions: 6.67% (1 / 15)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.c',function(){function makeCaseInsensitiveRegex(pattern){pattern=pattern.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');return new RegExp(pattern,'i');}function Filter(){}Filter.prototype={__proto__:Object.prototype,matchCounter:function(counter){return true;},matchCpu:function(cpu){return true;},matchProcess:function(process){return true;},matchSlice:function(slice){return true;},matchThread:function(thread){return true;}};function TitleOrCategoryFilter(text){Filter.call(this);this.regex_=makeCaseInsensitiveRegex(text);if(!text.length)throw new Error('Filter text is empty.');}TitleOrCategoryFilter.prototype={__proto__:Filter.prototype,matchSlice:function(slice){if(slice.title===undefined&&slice.category===undefined)return false;return this.regex_.test(slice.title)||!!slice.category&&this.regex_.test(slice.category);}};function ExactTitleFilter(text){Filter.call(this);this.text_=text;if(!text.length)throw new Error('Filter text is empty.');}ExactTitleFilter.prototype={__proto__:Filter.prototype,matchSlice:function(slice){return slice.title===this.text_;}};function FullTextFilter(text){Filter.call(this);this.regex_=makeCaseInsensitiveRegex(text);this.titleOrCategoryFilter_=new TitleOrCategoryFilter(text);}FullTextFilter.prototype={__proto__:Filter.prototype,matchObject_:function(obj){for(var key in obj){if(!obj.hasOwnProperty(key))continue;if(this.regex_.test(key))return true;if(this.regex_.test(obj[key]))return true;}return false;},matchSlice:function(slice){if(this.titleOrCategoryFilter_.matchSlice(slice))return true;return this.matchObject_(slice.args);}};return{Filter:Filter,TitleOrCategoryFilter:TitleOrCategoryFilter,ExactTitleFilter:ExactTitleFilter,FullTextFilter:FullTextFilter};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/
File Statements Branches Functions Lines
lean_config.js 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/lean_config.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/lean_config.js

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./importer/trace_event_importer.js");require("../model/model.js");
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/chrome/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/chrome/

Statements: 68.29% (28 / 41)      Branches: 20% (2 / 10)      Functions: 60% (3 / 5)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/chrome/
File Statements Branches Functions Lines
chrome_user_friendly_category_driver.js 68.29% (28 / 41) 20% (2 / 10) 60% (3 / 5) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/chrome/chrome_user_friendly_category_driver.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/chrome/chrome_user_friendly_category_driver.js

Statements: 68.29% (28 / 41)      Branches: 20% (2 / 10)      Functions: 60% (3 / 5)      Lines: 100% (1 / 1)      Ignored: none     

1 272  
"use strict";require("../../base/event.js");require("../../base/iteration_helpers.js");require("../../base/sinebow_color_generator.js");'use strict';global.tr.exportTo('tr.e.chrome',function(){var SAME_AS_PARENT='same-as-parent';var TITLES_FOR_USER_FRIENDLY_CATEGORY={composite:['CompositingInputsUpdater::update','ThreadProxy::SetNeedsUpdateLayers','LayerTreeHost::UpdateLayers::CalcDrawProps','UpdateLayerTree'],gc:['minorGC','majorGC','MajorGC','MinorGC','V8.GCScavenger','V8.GCIncrementalMarking','V8.GCIdleNotification','V8.GCContext','V8.GCCompactor','V8GCController::traceDOMWrappers'],iframe_creation:['WebLocalFrameImpl::createChildframe'],imageDecode:['Decode Image','ImageFrameGenerator::decode','ImageFrameGenerator::decodeAndScale'],input:['HitTest','ScrollableArea::scrollPositionChanged','EventHandler::handleMouseMoveEvent'],layout:['FrameView::invalidateTree','FrameView::layout','FrameView::performLayout','FrameView::performPostLayoutTasks','FrameView::performPreLayoutTasks','Layer::updateLayerPositionsAfterLayout','Layout','LayoutView::hitTest','ResourceLoadPriorityOptimizer::updateAllImageResourcePriorities','WebViewImpl::layout'],parseHTML:['ParseHTML','HTMLDocumentParser::didReceiveParsedChunkFromBackgroundParser','HTMLDocumentParser::processParsedChunkFromBackgroundParser'],raster:['DisplayListRasterSource::PerformSolidColorAnalysis','Picture::Raster','RasterBufferImpl::Playback','RasterTask','RasterizerTaskImpl::RunOnWorkerThread','SkCanvas::drawImageRect()','SkCanvas::drawPicture()','SkCanvas::drawTextBlob()','TileTaskWorkerPool::PlaybackToMemory'],record:['ContentLayerDelegate::paintContents','DeprecatedPaintLayerCompositor::updateIfNeededRecursive','DeprecatedPaintLayerCompositor::updateLayerPositionsAfterLayout','Paint','Picture::Record','PictureLayer::Update','RenderLayer::updateLayerPositionsAfterLayout'],style:['CSSParserImpl::parseStyleSheet.parse','CSSParserImpl::parseStyleSheet.tokenize','Document::updateStyle','Document::updateStyleInvalidationIfNeeded','ParseAuthorStyleSheet','RuleSet::addRulesFromSheet','StyleElement::processStyleSheet','StyleEngine::createResolver','StyleSheetContents::parseAuthorStyleSheet','UpdateLayoutTree'],script_parse_and_compile:['v8.parseOnBackground','V8.ScriptCompiler'],script_execute:['V8.Execute','WindowProxy::initialize'],resource_loading:['ResourceFetcher::requestResource','ResourceDispatcher::OnReceivedData','ResourceDispatcher::OnRequestComplete','ResourceDispatcher::OnReceivedResponse','Resource::appendData'],renderer_misc:['DecodeFont','ThreadState::completeSweep'],v8_runtime:[],[SAME_AS_PARENT]:['SyncChannel::Send']};var COLOR_FOR_USER_FRIENDLY_CATEGORY=new tr.b.SinebowColorGenerator();var USER_FRIENDLY_CATEGORY_FOR_TITLE=new Map();for(var category in TITLES_FOR_USER_FRIENDLY_CATEGORY){TITLES_FOR_USER_FRIENDLY_CATEGORY[category].forEach(function(title){USER_FRIENDLY_CATEGORY_FOR_TITLE.set(title,category);});}var USER_FRIENDLY_CATEGORY_FOR_EVENT_CATEGORY={netlog:'net',overhead:'overhead',startup:'startup',gpu:'gpu'};function ChromeUserFriendlyCategoryDriver(){}ChromeUserFriendlyCategoryDriver.fromEvent=function(event){var userFriendlyCategory=USER_FRIENDLY_CATEGORY_FOR_TITLE.get(event.title);if(userFriendlyCategory){if(userFriendlyCategory==SAME_AS_PARENT){if(event.parentSlice)return ChromeUserFriendlyCategoryDriver.fromEvent(event.parentSlice);}else{return userFriendlyCategory;}}var eventCategoryParts=tr.b.getCategoryParts(event.category);for(var i=0;i<eventCategoryParts.length;++i){var eventCategory=eventCategoryParts[i];userFriendlyCategory=USER_FRIENDLY_CATEGORY_FOR_EVENT_CATEGORY[eventCategory];if(userFriendlyCategory)return userFriendlyCategory;}return'other';};ChromeUserFriendlyCategoryDriver.getColor=function(ufc){return COLOR_FOR_USER_FRIENDLY_CATEGORY.colorForKey(ufc);};ChromeUserFriendlyCategoryDriver.ALL_TITLES=['other'];for(var category in TITLES_FOR_USER_FRIENDLY_CATEGORY){if(category===SAME_AS_PARENT)continue;ChromeUserFriendlyCategoryDriver.ALL_TITLES.push(category);}for(var category of tr.b.dictionaryValues(USER_FRIENDLY_CATEGORY_FOR_EVENT_CATEGORY)){ChromeUserFriendlyCategoryDriver.ALL_TITLES.push(category);}ChromeUserFriendlyCategoryDriver.ALL_TITLES.sort();for(var category of ChromeUserFriendlyCategoryDriver.ALL_TITLES)ChromeUserFriendlyCategoryDriver.getColor(category);return{ChromeUserFriendlyCategoryDriver:ChromeUserFriendlyCategoryDriver};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/chrome/cc/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/chrome/cc/

Statements: 9.69% (25 / 258)      Branches: 0% (0 / 151)      Functions: 6.06% (2 / 33)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/chrome/cc/
File Statements Branches Functions Lines
input_latency_async_slice.js 9.69% (25 / 258) 0% (0 / 151) 6.06% (2 / 33) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/chrome/cc/input_latency_async_slice.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/chrome/cc/input_latency_async_slice.js

Statements: 9.69% (25 / 258)      Branches: 0% (0 / 151)      Functions: 6.06% (2 / 33)      Lines: 100% (1 / 1)      Ignored: none     

1 229  
"use strict";require("../../../model/async_slice.js");require("../../../model/event_set.js");require("../../../model/helpers/chrome_model_helper.js");'use strict';global.tr.exportTo('tr.e.cc',function(){var AsyncSlice=tr.model.AsyncSlice;var EventSet=tr.model.EventSet;var UI_COMP_NAME='INPUT_EVENT_LATENCY_UI_COMPONENT';var ORIGINAL_COMP_NAME='INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT';var BEGIN_COMP_NAME='INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT';var END_COMP_NAME='INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT';var MAIN_RENDERER_THREAD_NAME='CrRendererMain';var COMPOSITOR_THREAD_NAME='Compositor';var POSTTASK_FLOW_EVENT='disabled-by-default-toplevel.flow';var IPC_FLOW_EVENT='disabled-by-default-ipc.flow';var INPUT_EVENT_TYPE_NAMES={CHAR:'Char',CLICK:'GestureClick',CONTEXT_MENU:'ContextMenu',FLING_CANCEL:'GestureFlingCancel',FLING_START:'GestureFlingStart',KEY_DOWN:'KeyDown',KEY_DOWN_RAW:'RawKeyDown',KEY_UP:'KeyUp',LATENCY_SCROLL_UPDATE:'ScrollUpdate',MOUSE_DOWN:'MouseDown',MOUSE_ENTER:'MouseEnter',MOUSE_LEAVE:'MouseLeave',MOUSE_MOVE:'MouseMove',MOUSE_UP:'MouseUp',MOUSE_WHEEL:'MouseWheel',PINCH_BEGIN:'GesturePinchBegin',PINCH_END:'GesturePinchEnd',PINCH_UPDATE:'GesturePinchUpdate',SCROLL_BEGIN:'GestureScrollBegin',SCROLL_END:'GestureScrollEnd',SCROLL_UPDATE:'GestureScrollUpdate',SCROLL_UPDATE_RENDERER:'ScrollUpdate',SHOW_PRESS:'GestureShowPress',TAP:'GestureTap',TAP_CANCEL:'GestureTapCancel',TAP_DOWN:'GestureTapDown',TOUCH_CANCEL:'TouchCancel',TOUCH_END:'TouchEnd',TOUCH_MOVE:'TouchMove',TOUCH_START:'TouchStart',UNKNOWN:'UNKNOWN'};function InputLatencyAsyncSlice(){AsyncSlice.apply(this,arguments);this.associatedEvents_=new EventSet();this.typeName_=undefined;if(!this.isLegacyEvent)this.determineModernTypeName_();}InputLatencyAsyncSlice.prototype={__proto__:AsyncSlice.prototype,get isLegacyEvent(){return this.title==='InputLatency';},get typeName(){if(!this.typeName_)this.determineLegacyTypeName_();return this.typeName_;},checkTypeName_:function(){if(!this.typeName_)throw'Unable to determine typeName';var found=false;for(var typeName in INPUT_EVENT_TYPE_NAMES){if(this.typeName===INPUT_EVENT_TYPE_NAMES[typeName]){found=true;break;}}if(!found)this.typeName_=INPUT_EVENT_TYPE_NAMES.UNKNOWN;},determineModernTypeName_:function(){var lastColonIndex=this.title.lastIndexOf(':');if(lastColonIndex<0)return;var characterAfterLastColonIndex=lastColonIndex+1;this.typeName_=this.title.slice(characterAfterLastColonIndex);this.checkTypeName_();},determineLegacyTypeName_:function(){for(var subSlice of this.enumerateAllDescendents()){var subSliceIsAInputLatencyAsyncSlice=subSlice instanceof InputLatencyAsyncSlice;if(!subSliceIsAInputLatencyAsyncSlice)continue;if(!subSlice.typeName)continue;if(this.typeName_&&subSlice.typeName_){var subSliceHasDifferentTypeName=this.typeName_!==subSlice.typeName_;if(subSliceHasDifferentTypeName){throw'InputLatencyAsyncSlice.determineLegacyTypeName_() '+' found multiple typeNames';}}this.typeName_=subSlice.typeName_;}if(!this.typeName_)throw'InputLatencyAsyncSlice.determineLegacyTypeName_() failed';this.checkTypeName_();},getRendererHelper:function(sourceSlices){var traceModel=this.startThread.parent.model;var modelHelper=traceModel.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);if(!modelHelper)return undefined;var mainThread=undefined;var compositorThread=undefined;for(var i in sourceSlices){if(sourceSlices[i].parentContainer.name===MAIN_RENDERER_THREAD_NAME)mainThread=sourceSlices[i].parentContainer;else if(sourceSlices[i].parentContainer.name===COMPOSITOR_THREAD_NAME)compositorThread=sourceSlices[i].parentContainer;if(mainThread&&compositorThread)break;}var rendererHelpers=modelHelper.rendererHelpers;var pids=Object.keys(rendererHelpers);for(var i=0;i<pids.length;i++){var pid=pids[i];var rendererHelper=rendererHelpers[pid];if(rendererHelper.mainThread===mainThread||rendererHelper.compositorThread===compositorThread)return rendererHelper;}return undefined;},addEntireSliceHierarchy:function(slice){this.associatedEvents_.push(slice);slice.iterateAllSubsequentSlices(function(subsequentSlice){this.associatedEvents_.push(subsequentSlice);},this);},addDirectlyAssociatedEvents:function(flowEvents){var slices=[];flowEvents.forEach(function(flowEvent){this.associatedEvents_.push(flowEvent);var newSource=flowEvent.startSlice.mostTopLevelSlice;if(slices.indexOf(newSource)===-1)slices.push(newSource);},this);var lastFlowEvent=flowEvents[flowEvents.length-1];var lastSource=lastFlowEvent.endSlice.mostTopLevelSlice;if(slices.indexOf(lastSource)===-1)slices.push(lastSource);return slices;},addScrollUpdateEvents:function(rendererHelper){if(!rendererHelper||!rendererHelper.compositorThread)return;var compositorThread=rendererHelper.compositorThread;var gestureScrollUpdateStart=this.start;var gestureScrollUpdateEnd=this.end;var allCompositorAsyncSlices=compositorThread.asyncSliceGroup.slices;for(var i in allCompositorAsyncSlices){var slice=allCompositorAsyncSlices[i];if(slice.title!=='Latency::ScrollUpdate')continue;var parentId=slice.args.data.INPUT_EVENT_LATENCY_FORWARD_SCROLL_UPDATE_TO_MAIN_COMPONENT.sequence_number;if(parentId===undefined){if(slice.start<gestureScrollUpdateStart||slice.start>=gestureScrollUpdateEnd)continue;}else{if(parseInt(parentId)!==parseInt(this.id))continue;}slice.associatedEvents.forEach(function(event){this.associatedEvents_.push(event);},this);break;}},belongToOtherInputs:function(slice,flowEvents){var fromOtherInputs=false;slice.iterateEntireHierarchy(function(subsequentSlice){if(fromOtherInputs)return;subsequentSlice.inFlowEvents.forEach(function(inflow){if(fromOtherInputs)return;if(inflow.category.indexOf('input')>-1){if(flowEvents.indexOf(inflow)===-1)fromOtherInputs=true;}},this);},this);return fromOtherInputs;},triggerOtherInputs:function(event,flowEvents){if(event.outFlowEvents===undefined||event.outFlowEvents.length===0)return false;var flow=event.outFlowEvents[0];if(flow.category!==POSTTASK_FLOW_EVENT||!flow.endSlice)return false;var endSlice=flow.endSlice;if(this.belongToOtherInputs(endSlice.mostTopLevelSlice,flowEvents))return true;return false;},followSubsequentSlices:function(event,queue,visited,flowEvents){var stopFollowing=false;var inputAck=false;event.iterateAllSubsequentSlices(function(slice){if(stopFollowing)return;if(slice.title==='TaskQueueManager::RunTask')return;if(slice.title==='ThreadProxy::ScheduledActionSendBeginMainFrame')return;if(slice.title==='Scheduler::ScheduleBeginImplFrameDeadline'){if(this.triggerOtherInputs(slice,flowEvents))return;}if(slice.title==='CompositorImpl::PostComposite'){if(this.triggerOtherInputs(slice,flowEvents))return;}if(slice.title==='InputRouterImpl::ProcessInputEventAck')inputAck=true;if(inputAck&&slice.title==='InputRouterImpl::FilterAndSendWebInputEvent')stopFollowing=true;this.followCurrentSlice(slice,queue,visited);},this);},followCurrentSlice:function(event,queue,visited){event.outFlowEvents.forEach(function(outflow){if((outflow.category===POSTTASK_FLOW_EVENT||outflow.category===IPC_FLOW_EVENT)&&outflow.endSlice){this.associatedEvents_.push(outflow);var nextEvent=outflow.endSlice.mostTopLevelSlice;if(!visited.contains(nextEvent)){visited.push(nextEvent);queue.push(nextEvent);}}},this);},backtraceFromDraw:function(beginImplFrame,visited){var pendingEventQueue=[];pendingEventQueue.push(beginImplFrame.mostTopLevelSlice);while(pendingEventQueue.length!==0){var event=pendingEventQueue.pop();this.addEntireSliceHierarchy(event);event.inFlowEvents.forEach(function(inflow){if(inflow.category===POSTTASK_FLOW_EVENT&&inflow.startSlice){var nextEvent=inflow.startSlice.mostTopLevelSlice;if(!visited.contains(nextEvent)){visited.push(nextEvent);pendingEventQueue.push(nextEvent);}}},this);}},sortRasterizerSlices:function(rasterWorkerThreads,sortedRasterizerSlices){rasterWorkerThreads.forEach(function(rasterizer){Array.prototype.push.apply(sortedRasterizerSlices,rasterizer.sliceGroup.slices);},this);sortedRasterizerSlices.sort(function(a,b){if(a.start!==b.start)return a.start-b.start;return a.guid-b.guid;});},addRasterizationEvents:function(prepareTiles,rendererHelper,visited,flowEvents,sortedRasterizerSlices){if(!prepareTiles.args.prepare_tiles_id)return;if(!rendererHelper||!rendererHelper.rasterWorkerThreads)return;var rasterWorkerThreads=rendererHelper.rasterWorkerThreads;var prepareTileId=prepareTiles.args.prepare_tiles_id;var pendingEventQueue=[];if(sortedRasterizerSlices.length===0)this.sortRasterizerSlices(rasterWorkerThreads,sortedRasterizerSlices);var numFinishedTasks=0;var RASTER_TASK_TITLE='RasterizerTaskImpl::RunOnWorkerThread';var IMAGEDECODE_TASK_TITLE='ImageDecodeTaskImpl::RunOnWorkerThread';var FINISHED_TASK_TITLE='TaskSetFinishedTaskImpl::RunOnWorkerThread';for(var i=0;i<sortedRasterizerSlices.length;i++){var task=sortedRasterizerSlices[i];if(task.title===RASTER_TASK_TITLE||task.title===IMAGEDECODE_TASK_TITLE){if(task.args.source_prepare_tiles_id===prepareTileId)this.addEntireSliceHierarchy(task.mostTopLevelSlice);}else if(task.title===FINISHED_TASK_TITLE){if(task.start>prepareTiles.start){pendingEventQueue.push(task.mostTopLevelSlice);if(++numFinishedTasks===3)break;}}}while(pendingEventQueue.length!=0){var event=pendingEventQueue.pop();this.addEntireSliceHierarchy(event);this.followSubsequentSlices(event,pendingEventQueue,visited,flowEvents);}},addOtherCausallyRelatedEvents:function(rendererHelper,sourceSlices,flowEvents,sortedRasterizerSlices){var pendingEventQueue=[];var visitedEvents=new EventSet();var beginImplFrame=undefined;var prepareTiles=undefined;var sortedRasterizerSlices=[];sourceSlices.forEach(function(sourceSlice){if(!visitedEvents.contains(sourceSlice)){visitedEvents.push(sourceSlice);pendingEventQueue.push(sourceSlice);}},this);while(pendingEventQueue.length!=0){var event=pendingEventQueue.pop();this.addEntireSliceHierarchy(event);this.followCurrentSlice(event,pendingEventQueue,visitedEvents);this.followSubsequentSlices(event,pendingEventQueue,visitedEvents,flowEvents);var COMPOSITOR_PREPARE_TILES='TileManager::PrepareTiles';prepareTiles=event.findDescendentSlice(COMPOSITOR_PREPARE_TILES);if(prepareTiles)this.addRasterizationEvents(prepareTiles,rendererHelper,visitedEvents,flowEvents,sortedRasterizerSlices);var COMPOSITOR_ON_BIFD='Scheduler::OnBeginImplFrameDeadline';beginImplFrame=event.findDescendentSlice(COMPOSITOR_ON_BIFD);if(beginImplFrame)this.backtraceFromDraw(beginImplFrame,visitedEvents);}var INPUT_GSU='InputLatency::GestureScrollUpdate';if(this.title===INPUT_GSU)this.addScrollUpdateEvents(rendererHelper);},get associatedEvents(){if(this.associatedEvents_.length!==0)return this.associatedEvents_;var modelIndices=this.startThread.parent.model.modelIndices;var flowEvents=modelIndices.getFlowEventsWithId(this.id);if(flowEvents.length===0)return this.associatedEvents_;var sourceSlices=this.addDirectlyAssociatedEvents(flowEvents);var rendererHelper=this.getRendererHelper(sourceSlices);this.addOtherCausallyRelatedEvents(rendererHelper,sourceSlices,flowEvents);return this.associatedEvents_;},get inputLatency(){if(!('data'in this.args))return undefined;var data=this.args.data;if(!(END_COMP_NAME in data))return undefined;var latency=0;var endTime=data[END_COMP_NAME].time;if(ORIGINAL_COMP_NAME in data){latency=endTime-data[ORIGINAL_COMP_NAME].time;}else if(UI_COMP_NAME in data){latency=endTime-data[UI_COMP_NAME].time;}else if(BEGIN_COMP_NAME in data){latency=endTime-data[BEGIN_COMP_NAME].time;}else{throw new Error('No valid begin latency component');}return latency;}};var eventTypeNames=['Char','ContextMenu','GestureClick','GestureFlingCancel','GestureFlingStart','GestureScrollBegin','GestureScrollEnd','GestureScrollUpdate','GestureShowPress','GestureTap','GestureTapCancel','GestureTapDown','GesturePinchBegin','GesturePinchEnd','GesturePinchUpdate','KeyDown','KeyUp','MouseDown','MouseEnter','MouseLeave','MouseMove','MouseUp','MouseWheel','RawKeyDown','ScrollUpdate','TouchCancel','TouchEnd','TouchMove','TouchStart'];var allTypeNames=['InputLatency'];eventTypeNames.forEach(function(eventTypeName){allTypeNames.push('InputLatency:'+eventTypeName);allTypeNames.push('InputLatency::'+eventTypeName);});AsyncSlice.subTypes.register(InputLatencyAsyncSlice,{typeNames:allTypeNames,categoryParts:['latencyInfo']});return{InputLatencyAsyncSlice:InputLatencyAsyncSlice,INPUT_EVENT_TYPE_NAMES:INPUT_EVENT_TYPE_NAMES};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/

Statements: 5.3% (77 / 1452)      Branches: 0% (0 / 790)      Functions: 2.86% (3 / 105)      Lines: 100% (3 / 3)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/
File Statements Branches Functions Lines
trace_code_entry.js 12.28% (7 / 57) 0% (0 / 28) 10% (1 / 10) 100% (1 / 1)
trace_code_map.js 13.79% (8 / 58) 0% (0 / 18) 6.67% (1 / 15) 100% (1 / 1)
trace_event_importer.js 4.64% (62 / 1337) 0% (0 / 744) 1.25% (1 / 80) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/trace_code_entry.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/trace_code_entry.js

Statements: 12.28% (7 / 57)      Branches: 0% (0 / 28)      Functions: 10% (1 / 10)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../model/source_info/js_source_info.js");'use strict';global.tr.exportTo('tr.e.importer',function(){function TraceCodeEntry(address,size,name,scriptId){this.id_=tr.b.GUID.allocateSimple();this.address_=address;this.size_=size;var rePrefix=/^(\w*:)?([*~]?)(.*)$/m;var tokens=rePrefix.exec(name);var prefix=tokens[1];var state=tokens[2];var body=tokens[3];if(state==='*'){state=tr.model.source_info.JSSourceState.OPTIMIZED;}else if(state==='~'){state=tr.model.source_info.JSSourceState.OPTIMIZABLE;}else if(state===''){state=tr.model.source_info.JSSourceState.COMPILED;}else{console.warning('Unknown v8 code state '+state);state=tr.model.source_info.JSSourceState.UNKNOWN;}var rawName;var rawUrl;if(prefix==='Script:'){rawName='';rawUrl=body;}else{var spacePos=body.lastIndexOf(' ');rawName=spacePos!==-1?body.substr(0,spacePos):body;rawUrl=spacePos!==-1?body.substr(spacePos+1):'';}function splitLineAndColumn(url){var lineColumnRegEx=/(?::(\d+))?(?::(\d+))?$/;var lineColumnMatch=lineColumnRegEx.exec(url);var lineNumber;var columnNumber;if(typeof lineColumnMatch[1]==='string'){lineNumber=parseInt(lineColumnMatch[1],10);lineNumber=isNaN(lineNumber)?undefined:lineNumber-1;}if(typeof lineColumnMatch[2]==='string'){columnNumber=parseInt(lineColumnMatch[2],10);columnNumber=isNaN(columnNumber)?undefined:columnNumber-1;}return{url:url.substring(0,url.length-lineColumnMatch[0].length),lineNumber:lineNumber,columnNumber:columnNumber};}var nativeSuffix=' native';var isNative=rawName.endsWith(nativeSuffix);this.name_=isNative?rawName.slice(0,-nativeSuffix.length):rawName;var urlData=splitLineAndColumn(rawUrl);var url=urlData.url||'';var line=urlData.lineNumber||0;var column=urlData.columnNumber||0;this.sourceInfo_=new tr.model.source_info.JSSourceInfo(url,line,column,isNative,scriptId,state);};TraceCodeEntry.prototype={get id(){return this.id_;},get sourceInfo(){return this.sourceInfo_;},get name(){return this.name_;},set address(address){this.address_=address;},get address(){return this.address_;},set size(size){this.size_=size;},get size(){return this.size_;}};return{TraceCodeEntry:TraceCodeEntry};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/trace_code_map.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/trace_code_map.js

Statements: 13.79% (8 / 58)      Branches: 0% (0 / 18)      Functions: 6.67% (1 / 15)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./trace_code_entry.js");'use strict';global.tr.exportTo('tr.e.importer',function(){function TraceCodeMap(){this.banks_=new Map();}TraceCodeMap.prototype={addEntry:function(addressHex,size,name,scriptId){var entry=new tr.e.importer.TraceCodeEntry(this.getAddress_(addressHex),size,name,scriptId);this.addEntry_(addressHex,entry);},moveEntry:function(oldAddressHex,newAddressHex,size){var entry=this.getBank_(oldAddressHex).removeEntry(this.getAddress_(oldAddressHex));if(!entry)return;entry.address=this.getAddress_(newAddressHex);entry.size=size;this.addEntry_(newAddressHex,entry);},lookupEntry:function(addressHex){return this.getBank_(addressHex).lookupEntry(this.getAddress_(addressHex));},addEntry_:function(addressHex,entry){this.getBank_(addressHex).addEntry(entry);},getAddress_:function(addressHex){var bankSizeHexDigits=13;addressHex=addressHex.slice(2);return parseInt(addressHex.slice(-bankSizeHexDigits),16);},getBank_:function(addressHex){addressHex=addressHex.slice(2);var bankSizeHexDigits=13;var maxHexDigits=16;var bankName=addressHex.slice(-maxHexDigits,-bankSizeHexDigits);var bank=this.banks_.get(bankName);if(!bank){bank=new TraceCodeBank();this.banks_.set(bankName,bank);}return bank;}};function TraceCodeBank(){this.entries_=[];}TraceCodeBank.prototype={removeEntry:function(address){if(this.entries_.length===0)return undefined;var index=tr.b.findLowIndexInSortedArray(this.entries_,function(entry){return entry.address;},address);var entry=this.entries_[index];if(!entry||entry.address!==address)return undefined;this.entries_.splice(index,1);return entry;},lookupEntry:function(address){var index=tr.b.findHighIndexInSortedArray(this.entries_,function(e){return address-e.address;})-1;var entry=this.entries_[index];return entry&&address<entry.address+entry.size?entry:undefined;},addEntry:function(newEntry){if(this.entries_.length===0)this.entries_.push(newEntry);var endAddress=newEntry.address+newEntry.size;var lastIndex=tr.b.findLowIndexInSortedArray(this.entries_,function(entry){return entry.address;},endAddress);var index;for(index=lastIndex-1;index>=0;--index){var entry=this.entries_[index];var entryEndAddress=entry.address+entry.size;if(entryEndAddress<=newEntry.address)break;}++index;this.entries_.splice(index,lastIndex-index,newEntry);}};return{TraceCodeMap:TraceCodeMap};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/trace_event_importer.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/trace_event_importer.js

Statements: 4.64% (62 / 1337)      Branches: 0% (0 / 744)      Functions: 1.25% (1 / 80)      Lines: 100% (1 / 1)      Ignored: none     

1 23  
"use strict";require("../../base/base64.js");require("../../base/color_scheme.js");require("../../base/range.js");require("../../base/unit.js");require("../../base/utils.js");require("./trace_code_entry.js");require("./trace_code_map.js");require("./v8/codemap.js");require("../../importer/context_processor.js");require("../../importer/importer.js");require("../../model/comment_box_annotation.js");require("../../model/constants.js");require("../../model/container_memory_dump.js");require("../../model/counter_series.js");require("../../model/flow_event.js");require("../../model/global_memory_dump.js");require("../../model/heap_dump.js");require("../../model/instant_event.js");require("../../model/memory_allocator_dump.js");require("../../model/model.js");require("../../model/process_memory_dump.js");require("../../model/rect_annotation.js");require("../../model/scoped_id.js");require("../../model/slice_group.js");require("../../model/vm_region.js");require("../../model/x_marker_annotation.js");require("../../value/numeric.js");'use strict';global.tr.exportTo('tr.e.importer',function(){var Base64=tr.b.Base64;var deepCopy=tr.b.deepCopy;var ColorScheme=tr.b.ColorScheme;function getEventColor(event,opt_customName){if(event.cname)return ColorScheme.getColorIdForReservedName(event.cname);else if(opt_customName||event.name){return ColorScheme.getColorIdForGeneralPurposeString(opt_customName||event.name);}}var PRODUCER='producer';var CONSUMER='consumer';var STEP='step';var BACKGROUND=tr.model.ContainerMemoryDump.LevelOfDetail.BACKGROUND;var LIGHT=tr.model.ContainerMemoryDump.LevelOfDetail.LIGHT;var DETAILED=tr.model.ContainerMemoryDump.LevelOfDetail.DETAILED;var MEMORY_DUMP_LEVEL_OF_DETAIL_ORDER=[undefined,BACKGROUND,LIGHT,DETAILED];var GLOBAL_MEMORY_ALLOCATOR_DUMP_PREFIX='global/';var ASYNC_CLOCK_SYNC_EVENT_TITLE_PREFIX='ClockSyncEvent.';var BYTE_STAT_NAME_MAP={'pc':'privateCleanResident','pd':'privateDirtyResident','sc':'sharedCleanResident','sd':'sharedDirtyResident','pss':'proportionalResident','sw':'swapped'};var WEAK_MEMORY_ALLOCATOR_DUMP_FLAG=1<<0;var OBJECT_TYPE_NAME_PATTERNS=[{prefix:'const char *WTF::getStringWithTypeName() [T = ',suffix:']'},{prefix:'const char* WTF::getStringWithTypeName() [with T = ',suffix:']'},{prefix:'const char *__cdecl WTF::getStringWithTypeName<',suffix:'>(void)'}];var SUBTRACE_FIELDS=new Set(['powerTraceAsString','systemTraceEvents']);var NON_METADATA_FIELDS=new Set(['samples','stackFrames','traceAnnotations','traceEvents']);for(var subtraceField in SUBTRACE_FIELDS)NON_METADATA_FIELDS.add(subtraceField);function TraceEventImporter(model,eventData){this.importPriority=1;this.model_=model;this.events_=undefined;this.sampleEvents_=undefined;this.stackFrameEvents_=undefined;this.subtraces_=[];this.eventsWereFromString_=false;this.softwareMeasuredCpuCount_=undefined;this.allAsyncEvents_=[];this.allFlowEvents_=[];this.allObjectEvents_=[];this.contextProcessorPerThread={};this.traceEventSampleStackFramesByName_={};this.v8ProcessCodeMaps_={};this.v8ProcessRootStackFrame_={};this.v8SamplingData_=[];this.asyncClockSyncStart_=undefined;this.asyncClockSyncFinish_=undefined;this.allMemoryDumpEvents_={};this.objectTypeNameMap_={};this.clockDomainId_=tr.model.ClockDomainId.UNKNOWN_CHROME_LEGACY;this.toModelTime_=undefined;if(typeof eventData==='string'||eventData instanceof String){eventData=eventData.trim();if(eventData[0]==='['){eventData=eventData.replace(/\s*,\s*$/,'');if(eventData[eventData.length-1]!==']')eventData=eventData+']';}this.events_=JSON.parse(eventData);this.eventsWereFromString_=true;}else{this.events_=eventData;}this.traceAnnotations_=this.events_.traceAnnotations;if(this.events_.traceEvents){var container=this.events_;this.events_=this.events_.traceEvents;for(var subtraceField of SUBTRACE_FIELDS)if(container[subtraceField])this.subtraces_.push(container[subtraceField]);this.sampleEvents_=container.samples;this.stackFrameEvents_=container.stackFrames;if(container.displayTimeUnit){var unitName=container.displayTimeUnit;var unit=tr.b.TimeDisplayModes[unitName];if(unit===undefined){throw new Error('Unit '+unitName+' is not supported.');}this.model_.intrinsicTimeUnit=unit;}for(var fieldName in container){if(NON_METADATA_FIELDS.has(fieldName))continue;this.model_.metadata.push({name:fieldName,value:container[fieldName]});if(fieldName==='metadata'){var metadata=container[fieldName];if(metadata['highres-ticks'])this.model_.isTimeHighResolution=metadata['highres-ticks'];if(metadata['clock-domain'])this.clockDomainId_=metadata['clock-domain'];}}}}TraceEventImporter.canImport=function(eventData){if(typeof eventData==='string'||eventData instanceof String){eventData=eventData.trim();return eventData[0]==='{'||eventData[0]==='[';}if(eventData instanceof Array&&eventData.length&&eventData[0].ph)return true;if(eventData.traceEvents){if(eventData.traceEvents instanceof Array){if(eventData.traceEvents.length&&eventData.traceEvents[0].ph)return true;if(eventData.samples.length&&eventData.stackFrames!==undefined)return true;}}return false;};TraceEventImporter.prototype={__proto__:tr.importer.Importer.prototype,get importerName(){return'TraceEventImporter';},extractSubtraces:function(){var subtraces=this.subtraces_;this.subtraces_=[];return subtraces;},deepCopyIfNeeded_:function(obj){if(obj===undefined)obj={};if(this.eventsWereFromString_)return obj;return deepCopy(obj);},deepCopyAlways_:function(obj){if(obj===undefined)obj={};return deepCopy(obj);},processAsyncEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);this.allAsyncEvents_.push({sequenceNumber:this.allAsyncEvents_.length,event:event,thread:thread});},processFlowEvent:function(event,opt_slice){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);this.allFlowEvents_.push({refGuid:tr.b.GUID.getLastSimpleGuid(),sequenceNumber:this.allFlowEvents_.length,event:event,slice:opt_slice,thread:thread});},processCounterEvent:function(event){var ctrName;if(event.id!==undefined)ctrName=event.name+'['+event.id+']';else ctrName=event.name;var ctr=this.model_.getOrCreateProcess(event.pid).getOrCreateCounter(event.cat,ctrName);var reservedColorId=event.cname?getEventColor(event):undefined;if(ctr.numSeries===0){for(var seriesName in event.args){var colorId=reservedColorId||getEventColor(event,ctr.name+'.'+seriesName);ctr.addSeries(new tr.model.CounterSeries(seriesName,colorId));}if(ctr.numSeries===0){this.model_.importWarning({type:'counter_parse_error',message:'Expected counter '+event.name+' to have at least one argument to use as a value.'});delete ctr.parent.counters[ctr.name];return;}}var ts=this.toModelTimeFromUs_(event.ts);ctr.series.forEach(function(series){var val=event.args[series.name]?event.args[series.name]:0;series.addCounterSample(ts,val);});},scopedIdForEvent_:function(event){return new tr.model.ScopedId(event.scope||tr.model.OBJECT_DEFAULT_SCOPE,event.id);},processObjectEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);this.allObjectEvents_.push({sequenceNumber:this.allObjectEvents_.length,event:event,thread:thread});if(thread.guid in this.contextProcessorPerThread){var processor=this.contextProcessorPerThread[thread.guid];var scopedId=this.scopedIdForEvent_(event);if(event.ph==='D')processor.destroyContext(scopedId);processor.invalidateContextCacheForSnapshot(scopedId);}},processContextEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);if(!(thread.guid in this.contextProcessorPerThread)){this.contextProcessorPerThread[thread.guid]=new tr.importer.ContextProcessor(this.model_);}var scopedId=this.scopedIdForEvent_(event);var contextType=event.name;var processor=this.contextProcessorPerThread[thread.guid];if(event.ph==='('){processor.enterContext(contextType,scopedId);}else if(event.ph===')'){processor.leaveContext(contextType,scopedId);}else{this.model_.importWarning({type:'unknown_context_phase',message:'Unknown context event phase: '+event.ph+'.'});}},setContextsFromThread_:function(thread,slice){if(thread.guid in this.contextProcessorPerThread){slice.contexts=this.contextProcessorPerThread[thread.guid].activeContexts;}},processDurationEvent:function(event){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);var ts=this.toModelTimeFromUs_(event.ts);if(!thread.sliceGroup.isTimestampValidForBeginOrEnd(ts)){this.model_.importWarning({type:'duration_parse_error',message:'Timestamps are moving backward.'});return;}if(event.ph==='B'){var slice=thread.sliceGroup.beginSlice(event.cat,event.name,this.toModelTimeFromUs_(event.ts),this.deepCopyIfNeeded_(event.args),this.toModelTimeFromUs_(event.tts),event.argsStripped,getEventColor(event));slice.startStackFrame=this.getStackFrameForEvent_(event);this.setContextsFromThread_(thread,slice);}else if(event.ph==='I'||event.ph==='i'||event.ph==='R'){if(event.s!==undefined&&event.s!=='t')throw new Error('This should never happen');thread.sliceGroup.beginSlice(event.cat,event.name,this.toModelTimeFromUs_(event.ts),this.deepCopyIfNeeded_(event.args),this.toModelTimeFromUs_(event.tts),event.argsStripped,getEventColor(event));var slice=thread.sliceGroup.endSlice(this.toModelTimeFromUs_(event.ts),this.toModelTimeFromUs_(event.tts));slice.startStackFrame=this.getStackFrameForEvent_(event);slice.endStackFrame=undefined;}else{if(!thread.sliceGroup.openSliceCount){this.model_.importWarning({type:'duration_parse_error',message:'E phase event without a matching B phase event.'});return;}var slice=thread.sliceGroup.endSlice(this.toModelTimeFromUs_(event.ts),this.toModelTimeFromUs_(event.tts),getEventColor(event));if(event.name&&slice.title!=event.name){this.model_.importWarning({type:'title_match_error',message:'Titles do not match. Title is '+slice.title+' in openSlice, and is '+event.name+' in endSlice'});}slice.endStackFrame=this.getStackFrameForEvent_(event);this.mergeArgsInto_(slice.args,event.args,slice.title);}},mergeArgsInto_:function(dstArgs,srcArgs,eventName){for(var arg in srcArgs){if(dstArgs[arg]!==undefined){this.model_.importWarning({type:'arg_merge_error',message:'Different phases of '+eventName+' provided values for argument '+arg+'.'+' The last provided value will be used.'});}dstArgs[arg]=this.deepCopyIfNeeded_(srcArgs[arg]);}},processCompleteEvent:function(event){if(event.cat!==undefined&&event.cat.indexOf('trace_event_overhead')>-1)return undefined;var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);if(event.flow_out){if(event.flow_in)event.flowPhase=STEP;else event.flowPhase=PRODUCER;}else if(event.flow_in){event.flowPhase=CONSUMER;}var slice=thread.sliceGroup.pushCompleteSlice(event.cat,event.name,this.toModelTimeFromUs_(event.ts),this.maybeToModelTimeFromUs_(event.dur),this.maybeToModelTimeFromUs_(event.tts),this.maybeToModelTimeFromUs_(event.tdur),this.deepCopyIfNeeded_(event.args),event.argsStripped,getEventColor(event),event.bind_id);slice.startStackFrame=this.getStackFrameForEvent_(event);slice.endStackFrame=this.getStackFrameForEvent_(event,true);this.setContextsFromThread_(thread,slice);return slice;},processJitCodeEvent:function(event){if(this.v8ProcessCodeMaps_[event.pid]===undefined)this.v8ProcessCodeMaps_[event.pid]=new tr.e.importer.TraceCodeMap();var map=this.v8ProcessCodeMaps_[event.pid];var data=event.args.data;if(event.name==='JitCodeMoved')map.moveEntry(data.code_start,data.new_code_start,data.code_len);else map.addEntry(data.code_start,data.code_len,data.name,data.script_id);},processMetadataEvent:function(event){if(event.name==='JitCodeAdded'||event.name==='JitCodeMoved'){this.v8SamplingData_.push(event);return;}if(event.argsStripped)return;if(event.name==='process_name'){var process=this.model_.getOrCreateProcess(event.pid);process.name=event.args.name;}else if(event.name==='process_labels'){var process=this.model_.getOrCreateProcess(event.pid);var labels=event.args.labels.split(',');for(var i=0;i<labels.length;i++)process.addLabelIfNeeded(labels[i]);}else if(event.name==='process_sort_index'){var process=this.model_.getOrCreateProcess(event.pid);process.sortIndex=event.args.sort_index;}else if(event.name==='thread_name'){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);thread.name=event.args.name;}else if(event.name==='thread_sort_index'){var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);thread.sortIndex=event.args.sort_index;}else if(event.name==='num_cpus'){var n=event.args.number;if(this.softwareMeasuredCpuCount_!==undefined)n=Math.max(n,this.softwareMeasuredCpuCount_);this.softwareMeasuredCpuCount_=n;}else if(event.name==='stackFrames'){var stackFrames=event.args.stackFrames;if(stackFrames===undefined){this.model_.importWarning({type:'metadata_parse_error',message:'No stack frames found in a \''+event.name+'\' metadata event'});}else{this.importStackFrames_(stackFrames,'p'+event.pid+':');}}else if(event.name==='typeNames'){var objectTypeNameMap=event.args.typeNames;if(objectTypeNameMap===undefined){this.model_.importWarning({type:'metadata_parse_error',message:'No mapping from object type IDs to names found in a \''+event.name+'\' metadata event'});}else{this.importObjectTypeNameMap_(objectTypeNameMap,event.pid);}}else if(event.name==='TraceConfig'){this.model_.metadata.push({name:'TraceConfig',value:event.args.value});}else{this.model_.importWarning({type:'metadata_parse_error',message:'Unrecognized metadata name: '+event.name});}},processInstantEvent:function(event){if(event.name==='JitCodeAdded'||event.name==='JitCodeMoved'){this.v8SamplingData_.push(event);return;}if(event.s==='t'||event.s===undefined){this.processDurationEvent(event);return;}var constructor;switch(event.s){case'g':constructor=tr.model.GlobalInstantEvent;break;case'p':constructor=tr.model.ProcessInstantEvent;break;default:this.model_.importWarning({type:'instant_parse_error',message:'I phase event with unknown "s" field value.'});return;}var instantEvent=new constructor(event.cat,event.name,getEventColor(event),this.toModelTimeFromUs_(event.ts),this.deepCopyIfNeeded_(event.args));switch(instantEvent.type){case tr.model.InstantEventType.GLOBAL:this.model_.instantEvents.push(instantEvent);break;case tr.model.InstantEventType.PROCESS:var process=this.model_.getOrCreateProcess(event.pid);process.instantEvents.push(instantEvent);break;default:throw new Error('Unknown instant event type: '+event.s);}},processV8Sample:function(event){var data=event.args.data;if(data.vm_state==='js'&&!data.stack.length)return;var rootStackFrame=this.v8ProcessRootStackFrame_[event.pid];if(!rootStackFrame){rootStackFrame=new tr.model.StackFrame(undefined,'v8-root-stack-frame','v8-root-stack-frame',0);this.v8ProcessRootStackFrame_[event.pid]=rootStackFrame;}function findChildWithEntryID(stackFrame,entryID){return tr.b.findFirstInArray(stackFrame.children,function(child){return child.entryID===entryID;});}var model=this.model_;function addStackFrame(lastStackFrame,entry){var childFrame=findChildWithEntryID(lastStackFrame,entry.id);if(childFrame)return childFrame;var frame=new tr.model.StackFrame(lastStackFrame,tr.b.GUID.allocateSimple(),entry.name,ColorScheme.getColorIdForGeneralPurposeString(entry.name),entry.sourceInfo);frame.entryID=entry.id;model.addStackFrame(frame);return frame;}var lastStackFrame=rootStackFrame;if(data.stack.length>0&&this.v8ProcessCodeMaps_[event.pid]){var map=this.v8ProcessCodeMaps_[event.pid];data.stack.reverse();for(var i=0;i<data.stack.length;i++){var entry=map.lookupEntry(data.stack[i]);if(entry===undefined){entry={id:'unknown',name:'unknown',sourceInfo:undefined};}lastStackFrame=addStackFrame(lastStackFrame,entry);}}else{var entry={id:data.vm_state,name:data.vm_state,sourceInfo:undefined};lastStackFrame=addStackFrame(lastStackFrame,entry);}var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);var sample=new tr.model.Sample(undefined,thread,'V8 Sample',this.toModelTimeFromUs_(event.ts),lastStackFrame,1,this.deepCopyIfNeeded_(event.args));this.model_.samples.push(sample);},processTraceSampleEvent:function(event){if(event.name==='V8Sample'){this.v8SamplingData_.push(event);return;}var stackFrame=this.getStackFrameForEvent_(event);if(stackFrame===undefined){stackFrame=this.traceEventSampleStackFramesByName_[event.name];}if(stackFrame===undefined){var id='te-'+tr.b.GUID.allocateSimple();stackFrame=new tr.model.StackFrame(undefined,id,event.name,ColorScheme.getColorIdForGeneralPurposeString(event.name));this.model_.addStackFrame(stackFrame);this.traceEventSampleStackFramesByName_[event.name]=stackFrame;}var thread=this.model_.getOrCreateProcess(event.pid).getOrCreateThread(event.tid);var sample=new tr.model.Sample(undefined,thread,'Trace Event Sample',this.toModelTimeFromUs_(event.ts),stackFrame,1,this.deepCopyIfNeeded_(event.args));this.setContextsFromThread_(thread,sample);this.model_.samples.push(sample);},processMemoryDumpEvent:function(event){if(event.ph!=='v')throw new Error('Invalid memory dump event phase "'+event.ph+'".');var dumpId=event.id;if(dumpId===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory dump event (phase \''+event.ph+'\') without a dump ID.'});return;}var pid=event.pid;if(pid===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory dump event (phase\''+event.ph+'\', dump ID \''+dumpId+'\') without a PID.'});return;}var allEvents=this.allMemoryDumpEvents_;var dumpIdEvents=allEvents[dumpId];if(dumpIdEvents===undefined)allEvents[dumpId]=dumpIdEvents={};var processEvents=dumpIdEvents[pid];if(processEvents===undefined)dumpIdEvents[pid]=processEvents=[];processEvents.push(event);},processClockSyncEvent:function(event){if(event.ph!=='c')throw new Error('Invalid clock sync event phase "'+event.ph+'".');var syncId=event.args.sync_id;if(syncId===undefined){this.model_.importWarning({type:'clock_sync_parse_error',message:'Clock sync at time '+event.ts+' without an ID.'});return;}if(event.args&&event.args.issue_ts!==undefined){this.model_.clockSyncManager.addClockSyncMarker(this.clockDomainId_,syncId,tr.b.Unit.timestampFromUs(event.args.issue_ts),tr.b.Unit.timestampFromUs(event.ts));}else{this.model_.clockSyncManager.addClockSyncMarker(this.clockDomainId_,syncId,tr.b.Unit.timestampFromUs(event.ts));}},processV8Events:function(){this.v8SamplingData_.sort(function(a,b){if(a.ts!==b.ts)return a.ts-b.ts;if(a.ph==='M'||a.ph==='I')return-1;else if(b.ph==='M'||b.ph==='I')return 1;return 0;});var length=this.v8SamplingData_.length;for(var i=0;i<length;++i){var event=this.v8SamplingData_[i];if(event.ph==='M'||event.ph==='I'){this.processJitCodeEvent(event);}else if(event.ph==='P'){this.processV8Sample(event);}}},initBackcompatClockSyncEventTracker_:function(event){if(event.name!==undefined&&event.name.startsWith(ASYNC_CLOCK_SYNC_EVENT_TITLE_PREFIX)&&event.ph==='S')this.asyncClockSyncStart_=event;if(event.name!==undefined&&event.name.startsWith(ASYNC_CLOCK_SYNC_EVENT_TITLE_PREFIX)&&event.ph==='F')this.asyncClockSyncFinish_=event;if(this.asyncClockSyncStart_==undefined||this.asyncClockSyncFinish_==undefined)return;var syncId=this.asyncClockSyncStart_.name.substring(ASYNC_CLOCK_SYNC_EVENT_TITLE_PREFIX.length);if(syncId!==this.asyncClockSyncFinish_.name.substring(ASYNC_CLOCK_SYNC_EVENT_TITLE_PREFIX.length)){throw new Error('Inconsistent clock sync id of async clock sync '+'events.');}var clockSyncEvent={ph:'c',args:{sync_id:syncId,issue_ts:this.asyncClockSyncStart_.ts},ts:this.asyncClockSyncFinish_.ts};this.asyncClockSyncStart_=undefined;this.asyncClockSyncFinish_=undefined;return clockSyncEvent;},importClockSyncMarkers:function(){var asyncClockSyncStart,asyncClockSyncFinish;for(var i=0;i<this.events_.length;i++){var event=this.events_[i];var possibleBackCompatClockSyncEvent=this.initBackcompatClockSyncEventTracker_(event);if(possibleBackCompatClockSyncEvent)this.processClockSyncEvent(possibleBackCompatClockSyncEvent);if(event.ph!=='c')continue;var eventSizeInBytes=this.model_.importOptions.trackDetailedModelStats?JSON.stringify(event).length:undefined;this.model_.stats.willProcessBasicTraceEvent('clock_sync',event.cat,event.name,event.ts,eventSizeInBytes);this.processClockSyncEvent(event);}},importEvents:function(){if(this.stackFrameEvents_)this.importStackFrames_(this.stackFrameEvents_,'g');if(this.traceAnnotations_)this.importAnnotations_();var importOptions=this.model_.importOptions;var trackDetailedModelStats=importOptions.trackDetailedModelStats;var modelStats=this.model_.stats;var events=this.events_;for(var eI=0;eI<events.length;eI++){var event=events[eI];if(event.args==='__stripped__'){event.argsStripped=true;event.args=undefined;}var eventSizeInBytes;if(trackDetailedModelStats)eventSizeInBytes=JSON.stringify(event).length;else eventSizeInBytes=undefined;if(event.ph==='B'||event.ph==='E'){modelStats.willProcessBasicTraceEvent('begin_end (non-compact)',event.cat,event.name,event.ts,eventSizeInBytes);this.processDurationEvent(event);}else if(event.ph==='X'){modelStats.willProcessBasicTraceEvent('begin_end (compact)',event.cat,event.name,event.ts,eventSizeInBytes);var slice=this.processCompleteEvent(event);if(slice!==undefined&&event.bind_id!==undefined)this.processFlowEvent(event,slice);}else if(event.ph==='b'||event.ph==='e'||event.ph==='n'||event.ph==='S'||event.ph==='F'||event.ph==='T'||event.ph==='p'){modelStats.willProcessBasicTraceEvent('async',event.cat,event.name,event.ts,eventSizeInBytes);this.processAsyncEvent(event);}else if(event.ph==='I'||event.ph==='i'||event.ph==='R'){modelStats.willProcessBasicTraceEvent('instant',event.cat,event.name,event.ts,eventSizeInBytes);this.processInstantEvent(event);}else if(event.ph==='P'){modelStats.willProcessBasicTraceEvent('samples',event.cat,event.name,event.ts,eventSizeInBytes);this.processTraceSampleEvent(event);}else if(event.ph==='C'){modelStats.willProcessBasicTraceEvent('counters',event.cat,event.name,event.ts,eventSizeInBytes);this.processCounterEvent(event);}else if(event.ph==='M'){modelStats.willProcessBasicTraceEvent('metadata',event.cat,event.name,event.ts,eventSizeInBytes);this.processMetadataEvent(event);}else if(event.ph==='N'||event.ph==='D'||event.ph==='O'){modelStats.willProcessBasicTraceEvent('objects',event.cat,event.name,event.ts,eventSizeInBytes);this.processObjectEvent(event);}else if(event.ph==='s'||event.ph==='t'||event.ph==='f'){modelStats.willProcessBasicTraceEvent('flows',event.cat,event.name,event.ts,eventSizeInBytes);this.processFlowEvent(event);}else if(event.ph==='v'){modelStats.willProcessBasicTraceEvent('memory_dumps',event.cat,event.name,event.ts,eventSizeInBytes);this.processMemoryDumpEvent(event);}else if(event.ph==='('||event.ph===')'){this.processContextEvent(event);}else if(event.ph==='c'){}else{modelStats.willProcessBasicTraceEvent('unknown',event.cat,event.name,event.ts,eventSizeInBytes);this.model_.importWarning({type:'parse_error',message:'Unrecognized event phase: '+event.ph+' ('+event.name+')'});}}this.processV8Events();tr.b.iterItems(this.v8ProcessRootStackFrame_,function(name,frame){frame.removeAllChildren();});},importStackFrames_:function(rawStackFrames,idPrefix){var model=this.model_;for(var id in rawStackFrames){var rawStackFrame=rawStackFrames[id];var fullId=idPrefix+id;var textForColor=rawStackFrame.category?rawStackFrame.category:rawStackFrame.name;var stackFrame=new tr.model.StackFrame(undefined,fullId,rawStackFrame.name,ColorScheme.getColorIdForGeneralPurposeString(textForColor));model.addStackFrame(stackFrame);}for(var id in rawStackFrames){var fullId=idPrefix+id;var stackFrame=model.stackFrames[fullId];if(stackFrame===undefined)throw new Error('Internal error');var rawStackFrame=rawStackFrames[id];var parentId=rawStackFrame.parent;var parentStackFrame;if(parentId===undefined){parentStackFrame=undefined;}else{var parentFullId=idPrefix+parentId;parentStackFrame=model.stackFrames[parentFullId];if(parentStackFrame===undefined){this.model_.importWarning({type:'metadata_parse_error',message:'Missing parent frame with ID '+parentFullId+' for stack frame \''+stackFrame.name+'\' (ID '+fullId+').'});}}stackFrame.parentFrame=parentStackFrame;}},importObjectTypeNameMap_:function(rawObjectTypeNameMap,pid){if(pid in this.objectTypeNameMap_){this.model_.importWarning({type:'metadata_parse_error',message:'Mapping from object type IDs to names provided for pid='+pid+' multiple times.'});return;}var objectTypeNamePrefix=undefined;var objectTypeNameSuffix=undefined;var objectTypeNameMap={};for(var objectTypeId in rawObjectTypeNameMap){var rawObjectTypeName=rawObjectTypeNameMap[objectTypeId];if(objectTypeNamePrefix===undefined){for(var i=0;i<OBJECT_TYPE_NAME_PATTERNS.length;i++){var pattern=OBJECT_TYPE_NAME_PATTERNS[i];if(rawObjectTypeName.startsWith(pattern.prefix)&&rawObjectTypeName.endsWith(pattern.suffix)){objectTypeNamePrefix=pattern.prefix;objectTypeNameSuffix=pattern.suffix;break;}}}if(objectTypeNamePrefix!==undefined&&rawObjectTypeName.startsWith(objectTypeNamePrefix)&&rawObjectTypeName.endsWith(objectTypeNameSuffix)){objectTypeNameMap[objectTypeId]=rawObjectTypeName.substring(objectTypeNamePrefix.length,rawObjectTypeName.length-objectTypeNameSuffix.length);}else{objectTypeNameMap[objectTypeId]=rawObjectTypeName;}}this.objectTypeNameMap_[pid]=objectTypeNameMap;},importAnnotations_:function(){for(var id in this.traceAnnotations_){var annotation=tr.model.Annotation.fromDictIfPossible(this.traceAnnotations_[id]);if(!annotation){this.model_.importWarning({type:'annotation_warning',message:'Unrecognized traceAnnotation typeName \"'+this.traceAnnotations_[id].typeName+'\"'});continue;}this.model_.addAnnotation(annotation);}},finalizeImport:function(){if(this.softwareMeasuredCpuCount_!==undefined){this.model_.kernel.softwareMeasuredCpuCount=this.softwareMeasuredCpuCount_;}this.createAsyncSlices_();this.createFlowSlices_();this.createExplicitObjects_();this.createImplicitObjects_();this.createMemoryDumps_();},getStackFrameForEvent_:function(event,opt_lookForEndEvent){var sf;var stack;if(opt_lookForEndEvent){sf=event.esf;stack=event.estack;}else{sf=event.sf;stack=event.stack;}if(stack!==undefined&&sf!==undefined){this.model_.importWarning({type:'stack_frame_and_stack_error',message:'Event at '+event.ts+' cannot have both a stack and a stackframe.'});return undefined;}if(stack!==undefined)return this.model_.resolveStackToStackFrame_(event.pid,stack);if(sf===undefined)return undefined;var stackFrame=this.model_.stackFrames['g'+sf];if(stackFrame===undefined){this.model_.importWarning({type:'sample_import_error',message:'No frame for '+sf});return;}return stackFrame;},resolveStackToStackFrame_:function(pid,stack){return undefined;},importSampleData:function(){if(!this.sampleEvents_)return;var m=this.model_;var events=this.sampleEvents_;if(this.events_.length===0){for(var i=0;i<events.length;i++){var event=events[i];m.getOrCreateProcess(event.tid).getOrCreateThread(event.tid);}}var threadsByTid={};m.getAllThreads().forEach(function(t){threadsByTid[t.tid]=t;});for(var i=0;i<events.length;i++){var event=events[i];var thread=threadsByTid[event.tid];if(thread===undefined){m.importWarning({type:'sample_import_error',message:'Thread '+events.tid+'not found'});continue;}var cpu;if(event.cpu!==undefined)cpu=m.kernel.getOrCreateCpu(event.cpu);var stackFrame=this.getStackFrameForEvent_(event);var sample=new tr.model.Sample(cpu,thread,event.name,this.toModelTimeFromUs_(event.ts),stackFrame,event.weight);m.samples.push(sample);}},createAsyncSlices_:function(){if(this.allAsyncEvents_.length===0)return;this.allAsyncEvents_.sort(function(x,y){var d=x.event.ts-y.event.ts;if(d!==0)return d;return x.sequenceNumber-y.sequenceNumber;});var legacyEvents=[];var nestableAsyncEventsByKey={};var nestableMeasureAsyncEventsByKey={};for(var i=0;i<this.allAsyncEvents_.length;i++){var asyncEventState=this.allAsyncEvents_[i];var event=asyncEventState.event;if(event.ph==='S'||event.ph==='F'||event.ph==='T'||event.ph==='p'){legacyEvents.push(asyncEventState);continue;}if(event.cat===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async events (ph: b, e, or n) require a '+'cat parameter.'});continue;}if(event.name===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async events (ph: b, e, or n) require a '+'name parameter.'});continue;}if(event.id===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async events (ph: b, e, or n) require an '+'id parameter.'});continue;}if(event.cat==='blink.user_timing'){var matched=/([^\/:]+):([^\/:]+)\/?(.*)/.exec(event.name);if(matched!==null){var key=matched[1]+':'+event.cat;event.args=JSON.parse(Base64.atob(matched[3])||'{}');if(nestableMeasureAsyncEventsByKey[key]===undefined)nestableMeasureAsyncEventsByKey[key]=[];nestableMeasureAsyncEventsByKey[key].push(asyncEventState);continue;}}var key=event.cat+':'+event.id;if(nestableAsyncEventsByKey[key]===undefined)nestableAsyncEventsByKey[key]=[];nestableAsyncEventsByKey[key].push(asyncEventState);}this.createLegacyAsyncSlices_(legacyEvents);this.createNestableAsyncSlices_(nestableMeasureAsyncEventsByKey);this.createNestableAsyncSlices_(nestableAsyncEventsByKey);},createLegacyAsyncSlices_:function(legacyEvents){if(legacyEvents.length===0)return;legacyEvents.sort(function(x,y){var d=x.event.ts-y.event.ts;if(d!=0)return d;return x.sequenceNumber-y.sequenceNumber;});var asyncEventStatesByNameThenID={};for(var i=0;i<legacyEvents.length;i++){var asyncEventState=legacyEvents[i];var event=asyncEventState.event;var name=event.name;if(name===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Async events (ph: S, T, p, or F) require a name '+' parameter.'});continue;}var id=event.id;if(id===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'Async events (ph: S, T, p, or F) require an id parameter.'});continue;}if(event.ph==='S'){if(asyncEventStatesByNameThenID[name]===undefined)asyncEventStatesByNameThenID[name]={};if(asyncEventStatesByNameThenID[name][id]){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.ts+', a slice of the same id '+id+' was alrady open.'});continue;}asyncEventStatesByNameThenID[name][id]=[];asyncEventStatesByNameThenID[name][id].push(asyncEventState);}else{if(asyncEventStatesByNameThenID[name]===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.ts+', no slice named '+name+' was open.'});continue;}if(asyncEventStatesByNameThenID[name][id]===undefined){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.ts+', no slice named '+name+' with id='+id+' was open.'});continue;}var events=asyncEventStatesByNameThenID[name][id];events.push(asyncEventState);if(event.ph==='F'){var asyncSliceConstructor=tr.model.AsyncSlice.subTypes.getConstructor(events[0].event.cat,name);var slice=new asyncSliceConstructor(events[0].event.cat,name,getEventColor(events[0].event),this.toModelTimeFromUs_(events[0].event.ts),tr.b.concatenateObjects(events[0].event.args,events[events.length-1].event.args),this.toModelTimeFromUs_(event.ts-events[0].event.ts),true,undefined,undefined,events[0].event.argsStripped);slice.startThread=events[0].thread;slice.endThread=asyncEventState.thread;slice.id=id;var stepType=events[1].event.ph;var isValid=true;for(var j=1;j<events.length-1;++j){if(events[j].event.ph==='T'||events[j].event.ph==='p'){isValid=this.assertStepTypeMatches_(stepType,events[j]);if(!isValid)break;}if(events[j].event.ph==='S'){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.event.ts+', a slice named '+event.event.name+' with id='+event.event.id+' had a step before the start event.'});continue;}if(events[j].event.ph==='F'){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.event.ts+', a slice named '+event.event.name+' with id='+event.event.id+' had a step after the finish event.'});continue;}var startIndex=j+(stepType==='T'?0:-1);var endIndex=startIndex+1;var subName=events[j].event.name;if(!events[j].event.argsStripped&&(events[j].event.ph==='T'||events[j].event.ph==='p'))subName=subName+':'+events[j].event.args.step;var asyncSliceConstructor=tr.model.AsyncSlice.subTypes.getConstructor(events[0].event.cat,subName);var subSlice=new asyncSliceConstructor(events[0].event.cat,subName,getEventColor(event,subName+j),this.toModelTimeFromUs_(events[startIndex].event.ts),this.deepCopyIfNeeded_(events[j].event.args),this.toModelTimeFromUs_(events[endIndex].event.ts-events[startIndex].event.ts),undefined,undefined,events[startIndex].event.argsStripped);subSlice.startThread=events[startIndex].thread;subSlice.endThread=events[endIndex].thread;subSlice.id=id;slice.subSlices.push(subSlice);}if(isValid){slice.startThread.asyncSliceGroup.push(slice);}delete asyncEventStatesByNameThenID[name][id];}}}},createNestableAsyncSlices_:function(nestableEventsByKey){for(var key in nestableEventsByKey){var eventStateEntries=nestableEventsByKey[key];var parentStack=[];for(var i=0;i<eventStateEntries.length;++i){var eventStateEntry=eventStateEntries[i];if(eventStateEntry.event.ph==='e'){var parentIndex=-1;for(var k=parentStack.length-1;k>=0;--k){if(parentStack[k].event.name===eventStateEntry.event.name){parentIndex=k;break;}}if(parentIndex===-1){eventStateEntry.finished=false;}else{parentStack[parentIndex].end=eventStateEntry;while(parentIndex<parentStack.length){parentStack.pop();}}}if(parentStack.length>0)eventStateEntry.parentEntry=parentStack[parentStack.length-1];if(eventStateEntry.event.ph==='b'){parentStack.push(eventStateEntry);}}var topLevelSlices=[];for(var i=0;i<eventStateEntries.length;++i){var eventStateEntry=eventStateEntries[i];if(eventStateEntry.event.ph==='e'&&eventStateEntry.finished===undefined){continue;}var startState=undefined;var endState=undefined;var sliceArgs=eventStateEntry.event.args||{};var sliceError=undefined;if(eventStateEntry.event.ph==='n'){startState=eventStateEntry;endState=eventStateEntry;}else if(eventStateEntry.event.ph==='b'){if(eventStateEntry.end===undefined){eventStateEntry.end=eventStateEntries[eventStateEntries.length-1];sliceError='Slice has no matching END. End time has been adjusted.';this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async BEGIN event at '+eventStateEntry.event.ts+' with name='+eventStateEntry.event.name+' and id='+eventStateEntry.event.id+' was unmatched.'});}else{function concatenateArguments(args1,args2){if(args1.params===undefined||args2.params===undefined)return tr.b.concatenateObjects(args1,args2);var args3={};args3.params=tr.b.concatenateObjects(args1.params,args2.params);return tr.b.concatenateObjects(args1,args2,args3);}var endArgs=eventStateEntry.end.event.args||{};sliceArgs=concatenateArguments(sliceArgs,endArgs);}startState=eventStateEntry;endState=eventStateEntry.end;}else{sliceError='Slice has no matching BEGIN. Start time has been adjusted.';this.model_.importWarning({type:'async_slice_parse_error',message:'Nestable async END event at '+eventStateEntry.event.ts+' with name='+eventStateEntry.event.name+' and id='+eventStateEntry.event.id+' was unmatched.'});startState=eventStateEntries[0];endState=eventStateEntry;}var isTopLevel=eventStateEntry.parentEntry===undefined;var asyncSliceConstructor=tr.model.AsyncSlice.subTypes.getConstructor(eventStateEntry.event.cat,eventStateEntry.event.name);var threadStart=undefined;var threadDuration=undefined;if(startState.event.tts&&startState.event.use_async_tts){threadStart=this.toModelTimeFromUs_(startState.event.tts);if(endState.event.tts){var threadEnd=this.toModelTimeFromUs_(endState.event.tts);threadDuration=threadEnd-threadStart;}}var slice=new asyncSliceConstructor(eventStateEntry.event.cat,eventStateEntry.event.name,getEventColor(endState.event),this.toModelTimeFromUs_(startState.event.ts),sliceArgs,this.toModelTimeFromUs_(endState.event.ts-startState.event.ts),isTopLevel,threadStart,threadDuration,startState.event.argsStripped);slice.startThread=startState.thread;slice.endThread=endState.thread;slice.startStackFrame=this.getStackFrameForEvent_(startState.event);slice.endStackFrame=this.getStackFrameForEvent_(endState.event);slice.id=key;if(sliceError!==undefined)slice.error=sliceError;eventStateEntry.slice=slice;if(isTopLevel){topLevelSlices.push(slice);}else if(eventStateEntry.parentEntry.slice!==undefined){eventStateEntry.parentEntry.slice.subSlices.push(slice);}}for(var si=0;si<topLevelSlices.length;si++){topLevelSlices[si].startThread.asyncSliceGroup.push(topLevelSlices[si]);}}},assertStepTypeMatches_:function(stepType,event){if(stepType!=event.event.ph){this.model_.importWarning({type:'async_slice_parse_error',message:'At '+event.event.ts+', a slice named '+event.event.name+' with id='+event.event.id+' had both begin and end steps, which is not allowed.'});return false;}return true;},createFlowSlices_:function(){if(this.allFlowEvents_.length===0)return;var that=this;function validateFlowEvent(){if(event.name===undefined){that.model_.importWarning({type:'flow_slice_parse_error',message:'Flow events (ph: s, t or f) require a name parameter.'});return false;}if(event.ph==='s'||event.ph==='f'||event.ph==='t'){if(event.id===undefined){that.model_.importWarning({type:'flow_slice_parse_error',message:'Flow events (ph: s, t or f) require an id parameter.'});return false;}return true;}if(event.bind_id){if(event.flow_in===undefined&&event.flow_out===undefined){that.model_.importWarning({type:'flow_slice_parse_error',message:'Flow producer or consumer require flow_in or flow_out.'});return false;}return true;}return false;}var createFlowEvent=function(thread,event,opt_slice){var startSlice,flowId,flowStartTs;if(event.bind_id){startSlice=opt_slice;flowId=event.bind_id;flowStartTs=this.toModelTimeFromUs_(event.ts+event.dur);}else{var ts=this.toModelTimeFromUs_(event.ts);startSlice=thread.sliceGroup.findSliceAtTs(ts);if(startSlice===undefined)return undefined;flowId=event.id;flowStartTs=ts;}var flowEvent=new tr.model.FlowEvent(event.cat,flowId,event.name,getEventColor(event),flowStartTs,that.deepCopyAlways_(event.args));flowEvent.startSlice=startSlice;flowEvent.startStackFrame=that.getStackFrameForEvent_(event);flowEvent.endStackFrame=undefined;startSlice.outFlowEvents.push(flowEvent);return flowEvent;}.bind(this);var finishFlowEventWith=function(flowEvent,thread,event,refGuid,bindToParent,opt_slice){var endSlice;if(event.bind_id){endSlice=opt_slice;}else{var ts=this.toModelTimeFromUs_(event.ts);if(bindToParent){endSlice=thread.sliceGroup.findSliceAtTs(ts);}else{endSlice=thread.sliceGroup.findNextSliceAfter(ts,refGuid);}if(endSlice===undefined)return false;}endSlice.inFlowEvents.push(flowEvent);flowEvent.endSlice=endSlice;flowEvent.duration=this.toModelTimeFromUs_(event.ts)-flowEvent.start;flowEvent.endStackFrame=that.getStackFrameForEvent_(event);that.mergeArgsInto_(flowEvent.args,event.args,flowEvent.title);return true;}.bind(this);function processFlowConsumer(flowIdToEvent,sliceGuidToEvent,event,slice){var flowEvent=flowIdToEvent[event.bind_id];if(flowEvent===undefined){that.model_.importWarning({type:'flow_slice_ordering_error',message:'Flow consumer '+event.bind_id+' does not have '+'a flow producer'});return false;}else if(flowEvent.endSlice){var flowProducer=flowEvent.startSlice;flowEvent=createFlowEvent(undefined,sliceGuidToEvent[flowProducer.guid],flowProducer);}var ok=finishFlowEventWith(flowEvent,undefined,event,refGuid,undefined,slice);if(ok){that.model_.flowEvents.push(flowEvent);}else{that.model_.importWarning({type:'flow_slice_end_error',message:'Flow consumer '+event.bind_id+' does not end '+'at an actual slice, so cannot be created.'});return false;}return true;}function processFlowProducer(flowIdToEvent,flowStatus,event,slice){if(flowIdToEvent[event.bind_id]&&flowStatus[event.bind_id]){that.model_.importWarning({type:'flow_slice_start_error',message:'Flow producer '+event.bind_id+' already seen'});return false;}var flowEvent=createFlowEvent(undefined,event,slice);if(!flowEvent){that.model_.importWarning({type:'flow_slice_start_error',message:'Flow producer '+event.bind_id+' does not start'+'a flow'});return false;}flowIdToEvent[event.bind_id]=flowEvent;}this.allFlowEvents_.sort(function(x,y){var d=x.event.ts-y.event.ts;if(d!=0)return d;return x.sequenceNumber-y.sequenceNumber;});var flowIdToEvent={};var sliceGuidToEvent={};var flowStatus={};for(var i=0;i<this.allFlowEvents_.length;++i){var data=this.allFlowEvents_[i];var refGuid=data.refGuid;var event=data.event;var thread=data.thread;if(!validateFlowEvent(event))continue;if(event.bind_id){var slice=data.slice;sliceGuidToEvent[slice.guid]=event;if(event.flowPhase===PRODUCER){if(!processFlowProducer(flowIdToEvent,flowStatus,event,slice))continue;flowStatus[event.bind_id]=true;}else{if(!processFlowConsumer(flowIdToEvent,sliceGuidToEvent,event,slice))continue;flowStatus[event.bind_id]=false;if(event.flowPhase===STEP){if(!processFlowProducer(flowIdToEvent,flowStatus,event,slice))continue;flowStatus[event.bind_id]=true;}}continue;}var flowEvent;if(event.ph==='s'){if(flowIdToEvent[event.id]){this.model_.importWarning({type:'flow_slice_start_error',message:'event id '+event.id+' already seen when '+'encountering start of flow event.'});continue;}flowEvent=createFlowEvent(thread,event);if(!flowEvent){this.model_.importWarning({type:'flow_slice_start_error',message:'event id '+event.id+' does not start '+'at an actual slice, so cannot be created.'});continue;}flowIdToEvent[event.id]=flowEvent;}else if(event.ph==='t'||event.ph==='f'){flowEvent=flowIdToEvent[event.id];if(flowEvent===undefined){this.model_.importWarning({type:'flow_slice_ordering_error',message:'Found flow phase '+event.ph+' for id: '+event.id+' but no flow start found.'});continue;}var bindToParent=event.ph==='t';if(event.ph==='f'){if(event.bp===undefined){if(event.cat.indexOf('input')>-1)bindToParent=true;else if(event.cat.indexOf('ipc.flow')>-1)bindToParent=true;}else{if(event.bp!=='e'){this.model_.importWarning({type:'flow_slice_bind_point_error',message:'Flow event with invalid binding point (event.bp).'});continue;}bindToParent=true;}}var ok=finishFlowEventWith(flowEvent,thread,event,refGuid,bindToParent);if(ok){that.model_.flowEvents.push(flowEvent);}else{this.model_.importWarning({type:'flow_slice_end_error',message:'event id '+event.id+' does not end '+'at an actual slice, so cannot be created.'});}flowIdToEvent[event.id]=undefined;if(ok&&event.ph==='t'){flowEvent=createFlowEvent(thread,event);flowIdToEvent[event.id]=flowEvent;}}}},createExplicitObjects_:function(){if(this.allObjectEvents_.length===0)return;var processEvent=function(objectEventState){var event=objectEventState.event;var scopedId=this.scopedIdForEvent_(event);var thread=objectEventState.thread;if(event.name===undefined){this.model_.importWarning({type:'object_parse_error',message:'While processing '+JSON.stringify(event)+': '+'Object events require an name parameter.'});}if(scopedId.id===undefined){this.model_.importWarning({type:'object_parse_error',message:'While processing '+JSON.stringify(event)+': '+'Object events require an id parameter.'});}var process=thread.parent;var ts=this.toModelTimeFromUs_(event.ts);var instance;if(event.ph==='N'){try{instance=process.objects.idWasCreated(scopedId,event.cat,event.name,ts);}catch(e){this.model_.importWarning({type:'object_parse_error',message:'While processing create of '+scopedId+' at ts='+ts+': '+e});return;}}else if(event.ph==='O'){if(event.args.snapshot===undefined){this.model_.importWarning({type:'object_parse_error',message:'While processing '+scopedId+' at ts='+ts+': '+'Snapshots must have args: {snapshot: ...}'});return;}var snapshot;try{var args=this.deepCopyIfNeeded_(event.args.snapshot);var cat;if(args.cat){cat=args.cat;delete args.cat;}else{cat=event.cat;}var baseTypename;if(args.base_type){baseTypename=args.base_type;delete args.base_type;}else{baseTypename=undefined;}snapshot=process.objects.addSnapshot(scopedId,cat,event.name,ts,args,baseTypename);snapshot.snapshottedOnThread=thread;}catch(e){this.model_.importWarning({type:'object_parse_error',message:'While processing snapshot of '+scopedId+' at ts='+ts+': '+e});return;}instance=snapshot.objectInstance;}else if(event.ph==='D'){try{process.objects.idWasDeleted(scopedId,event.cat,event.name,ts);var instanceMap=process.objects.getOrCreateInstanceMap_(scopedId);instance=instanceMap.lastInstance;}catch(e){this.model_.importWarning({type:'object_parse_error',message:'While processing delete of '+scopedId+' at ts='+ts+': '+e});return;}}if(instance)instance.colorId=getEventColor(event,instance.typeName);}.bind(this);this.allObjectEvents_.sort(function(x,y){var d=x.event.ts-y.event.ts;if(d!=0)return d;return x.sequenceNumber-y.sequenceNumber;});var allObjectEvents=this.allObjectEvents_;for(var i=0;i<allObjectEvents.length;i++){var objectEventState=allObjectEvents[i];try{processEvent.call(this,objectEventState);}catch(e){this.model_.importWarning({type:'object_parse_error',message:e.message});}}},createImplicitObjects_:function(){tr.b.iterItems(this.model_.processes,function(pid,process){this.createImplicitObjectsForProcess_(process);},this);},createImplicitObjectsForProcess_:function(process){function processField(referencingObject,referencingObjectFieldName,referencingObjectFieldValue,containingSnapshot){if(!referencingObjectFieldValue)return;if(referencingObjectFieldValue instanceof tr.model.ObjectSnapshot)return null;if(referencingObjectFieldValue.id===undefined)return;var implicitSnapshot=referencingObjectFieldValue;var rawId=implicitSnapshot.id;var m=/(.+)\/(.+)/.exec(rawId);if(!m)throw new Error('Implicit snapshots must have names.');delete implicitSnapshot.id;var name=m[1];var id=m[2];var res;var cat;if(implicitSnapshot.cat!==undefined)cat=implicitSnapshot.cat;else cat=containingSnapshot.objectInstance.category;var baseTypename;if(implicitSnapshot.base_type)baseTypename=implicitSnapshot.base_type;else baseTypename=undefined;var scope=containingSnapshot.objectInstance.scopedId.scope;try{res=process.objects.addSnapshot(new tr.model.ScopedId(scope,id),cat,name,containingSnapshot.ts,implicitSnapshot,baseTypename);}catch(e){this.model_.importWarning({type:'object_snapshot_parse_error',message:'While processing implicit snapshot of '+rawId+' at ts='+containingSnapshot.ts+': '+e});return;}res.objectInstance.hasImplicitSnapshots=true;res.containingSnapshot=containingSnapshot;res.snapshottedOnThread=containingSnapshot.snapshottedOnThread;referencingObject[referencingObjectFieldName]=res;if(!(res instanceof tr.model.ObjectSnapshot))throw new Error('Created object must be instanceof snapshot');return res.args;}function iterObject(object,func,containingSnapshot,thisArg){if(!(object instanceof Object))return;if(object instanceof Array){for(var i=0;i<object.length;i++){var res=func.call(thisArg,object,i,object[i],containingSnapshot);if(res===null)continue;if(res)iterObject(res,func,containingSnapshot,thisArg);else iterObject(object[i],func,containingSnapshot,thisArg);}return;}for(var key in object){var res=func.call(thisArg,object,key,object[key],containingSnapshot);if(res===null)continue;if(res)iterObject(res,func,containingSnapshot,thisArg);else iterObject(object[key],func,containingSnapshot,thisArg);}}process.objects.iterObjectInstances(function(instance){instance.snapshots.forEach(function(snapshot){if(snapshot.args.id!==undefined)throw new Error('args cannot have an id field inside it');iterObject(snapshot.args,processField,snapshot,this);},this);},this);},createMemoryDumps_:function(){for(var dumpId in this.allMemoryDumpEvents_)this.createGlobalMemoryDump_(this.allMemoryDumpEvents_[dumpId],dumpId);},createGlobalMemoryDump_:function(dumpIdEvents,dumpId){var globalRange=new tr.b.Range();for(var pid in dumpIdEvents){var processEvents=dumpIdEvents[pid];for(var i=0;i<processEvents.length;i++)globalRange.addValue(this.toModelTimeFromUs_(processEvents[i].ts));}if(globalRange.isEmpty)throw new Error('Internal error: Global memory dump without events');var globalMemoryDump=new tr.model.GlobalMemoryDump(this.model_,globalRange.min);globalMemoryDump.duration=globalRange.range;this.model_.globalMemoryDumps.push(globalMemoryDump);var globalMemoryAllocatorDumpsByFullName={};var levelsOfDetail={};var allMemoryAllocatorDumpsByGuid={};for(var pid in dumpIdEvents){this.createProcessMemoryDump_(globalMemoryDump,globalMemoryAllocatorDumpsByFullName,levelsOfDetail,allMemoryAllocatorDumpsByGuid,dumpIdEvents[pid],pid,dumpId);}globalMemoryDump.levelOfDetail=levelsOfDetail.global;globalMemoryDump.memoryAllocatorDumps=this.inferMemoryAllocatorDumpTree_(globalMemoryAllocatorDumpsByFullName);this.parseMemoryDumpAllocatorEdges_(allMemoryAllocatorDumpsByGuid,dumpIdEvents,dumpId);},createProcessMemoryDump_:function(globalMemoryDump,globalMemoryAllocatorDumpsByFullName,levelsOfDetail,allMemoryAllocatorDumpsByGuid,processEvents,pid,dumpId){var processRange=new tr.b.Range();for(var i=0;i<processEvents.length;i++)processRange.addValue(this.toModelTimeFromUs_(processEvents[i].ts));if(processRange.isEmpty)throw new Error('Internal error: Process memory dump without events');var process=this.model_.getOrCreateProcess(pid);var processMemoryDump=new tr.model.ProcessMemoryDump(globalMemoryDump,process,processRange.min);processMemoryDump.duration=processRange.range;process.memoryDumps.push(processMemoryDump);globalMemoryDump.processMemoryDumps[pid]=processMemoryDump;var processMemoryAllocatorDumpsByFullName={};for(var i=0;i<processEvents.length;i++){var processEvent=processEvents[i];var dumps=processEvent.args.dumps;if(dumps===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'\'dumps\' field not found in a process memory dump'+' event for PID='+pid+' and dump ID='+dumpId+'.'});continue;}this.parseMemoryDumpTotals_(processMemoryDump,dumps,pid,dumpId);this.parseMemoryDumpVmRegions_(processMemoryDump,dumps,pid,dumpId);this.parseMemoryDumpHeapDumps_(processMemoryDump,dumps,pid,dumpId);this.parseMemoryDumpLevelOfDetail_(levelsOfDetail,dumps,pid,dumpId);this.parseMemoryDumpAllocatorDumps_(processMemoryDump,globalMemoryDump,processMemoryAllocatorDumpsByFullName,globalMemoryAllocatorDumpsByFullName,allMemoryAllocatorDumpsByGuid,dumps,pid,dumpId);}if(levelsOfDetail.process===undefined){levelsOfDetail.process=processMemoryDump.vmRegions?DETAILED:LIGHT;}if(!this.updateMemoryDumpLevelOfDetail_(levelsOfDetail,'global',levelsOfDetail.process)){this.model_.importWarning({type:'memory_dump_parse_error',message:'diffent levels of detail provided for global memory'+' dump (dump ID='+dumpId+').'});}processMemoryDump.levelOfDetail=levelsOfDetail.process;delete levelsOfDetail.process;processMemoryDump.memoryAllocatorDumps=this.inferMemoryAllocatorDumpTree_(processMemoryAllocatorDumpsByFullName);},parseMemoryDumpTotals_:function(processMemoryDump,dumps,pid,dumpId){var rawTotals=dumps.process_totals;if(rawTotals===undefined)return;if(processMemoryDump.totals!==undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Process totals provided multiple times for'+' process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});return;}var totals={};var platformSpecificTotals=undefined;for(var rawTotalName in rawTotals){var rawTotalValue=rawTotals[rawTotalName];if(rawTotalValue===undefined)continue;if(rawTotalName==='resident_set_bytes'){totals.residentBytes=parseInt(rawTotalValue,16);continue;}if(rawTotalName==='peak_resident_set_bytes'){totals.peakResidentBytes=parseInt(rawTotalValue,16);continue;}if(rawTotalName==='is_peak_rss_resetable'){totals.arePeakResidentBytesResettable=!!rawTotalValue;continue;}if(platformSpecificTotals===undefined){platformSpecificTotals={};totals.platformSpecific=platformSpecificTotals;}platformSpecificTotals[rawTotalName]=parseInt(rawTotalValue,16);}if(totals.peakResidentBytes===undefined&&totals.arePeakResidentBytesResettable!==undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Optional field peak_resident_set_bytes found'+' but is_peak_rss_resetable not found in'+' process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});}if(totals.arePeakResidentBytesResettable!==undefined&&totals.peakResidentBytes===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Optional field is_peak_rss_resetable found'+' but peak_resident_set_bytes not found in'+' process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});}processMemoryDump.totals=totals;},parseMemoryDumpVmRegions_:function(processMemoryDump,dumps,pid,dumpId){var rawProcessMmaps=dumps.process_mmaps;if(rawProcessMmaps===undefined)return;var rawVmRegions=rawProcessMmaps.vm_regions;if(rawVmRegions===undefined)return;if(processMemoryDump.vmRegions!==undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'VM regions provided multiple times for'+' process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});return;}var vmRegions=new Array(rawVmRegions.length);for(var i=0;i<rawVmRegions.length;i++){var rawVmRegion=rawVmRegions[i];var byteStats={};var rawByteStats=rawVmRegion.bs;for(var rawByteStatName in rawByteStats){var rawByteStatValue=rawByteStats[rawByteStatName];if(rawByteStatValue===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Byte stat \''+rawByteStatName+'\' of VM region '+i+' ('+rawVmRegion.mf+') in process memory dump for '+'PID='+pid+' and dump ID='+dumpId+' does not have a value.'});continue;}var byteStatName=BYTE_STAT_NAME_MAP[rawByteStatName];if(byteStatName===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Unknown byte stat name \''+rawByteStatName+'\' ('+rawByteStatValue+') of VM region '+i+' ('+rawVmRegion.mf+') in process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});continue;}byteStats[byteStatName]=parseInt(rawByteStatValue,16);}vmRegions[i]=new tr.model.VMRegion(parseInt(rawVmRegion.sa,16),parseInt(rawVmRegion.sz,16),rawVmRegion.pf,rawVmRegion.mf,byteStats);}processMemoryDump.vmRegions=tr.model.VMRegionClassificationNode.fromRegions(vmRegions);},parseMemoryDumpHeapDumps_:function(processMemoryDump,dumps,pid,dumpId){var rawHeapDumps=dumps.heaps;if(rawHeapDumps===undefined)return;if(processMemoryDump.heapDumps!==undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Heap dumps provided multiple times for'+' process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});return;}var model=this.model_;var idPrefix='p'+pid+':';var heapDumps={};var objectTypeNameMap=this.objectTypeNameMap_[pid];if(objectTypeNameMap===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Missing mapping from object type IDs to names.'});}for(var allocatorName in rawHeapDumps){var entries=rawHeapDumps[allocatorName].entries;if(entries===undefined||entries.length===0){this.model_.importWarning({type:'memory_dump_parse_error',message:'No heap entries in a '+allocatorName+' heap dump for PID='+pid+' and dump ID='+dumpId+'.'});continue;}var isOldFormat=entries[0].bt===undefined;if(!isOldFormat&&objectTypeNameMap===undefined){continue;}var heapDump=new tr.model.HeapDump(processMemoryDump,allocatorName);for(var i=0;i<entries.length;i++){var entry=entries[i];var leafStackFrameIndex=entry.bt;var leafStackFrame;if(isOldFormat){if(leafStackFrameIndex===undefined){leafStackFrame=undefined;}else{var leafStackFrameId=idPrefix+leafStackFrameIndex;if(leafStackFrameIndex===''){leafStackFrame=undefined;}else{leafStackFrame=model.stackFrames[leafStackFrameId];if(leafStackFrame===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Missing leaf stack frame (ID '+leafStackFrameId+') of heap entry '+i+' (size '+size+') in a '+allocatorName+' heap dump for PID='+pid+'.'});continue;}}leafStackFrameId+=':self';if(model.stackFrames[leafStackFrameId]!==undefined){leafStackFrame=model.stackFrames[leafStackFrameId];}else{leafStackFrame=new tr.model.StackFrame(leafStackFrame,leafStackFrameId,'<self>',undefined);model.addStackFrame(leafStackFrame);}}}else{if(leafStackFrameIndex===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Missing stack frame ID of heap entry '+i+' (size '+size+') in a '+allocatorName+' heap dump for PID='+pid+'.'});continue;}var leafStackFrameId=idPrefix+leafStackFrameIndex;if(leafStackFrameIndex===''){leafStackFrame=undefined;}else{leafStackFrame=model.stackFrames[leafStackFrameId];if(leafStackFrame===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Missing leaf stack frame (ID '+leafStackFrameId+') of heap entry '+i+' (size '+size+') in a '+allocatorName+' heap dump for PID='+pid+'.'});continue;}}}var objectTypeId=entry.type;var objectTypeName;if(objectTypeId===undefined){objectTypeName=undefined;}else if(objectTypeNameMap===undefined){continue;}else{objectTypeName=objectTypeNameMap[objectTypeId];if(objectTypeName===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Missing object type name (ID '+objectTypeId+') of heap entry '+i+' (size '+size+') in a '+allocatorName+' heap dump for pid='+pid+'.'});continue;}}var size=parseInt(entry.size,16);var count=entry.count===undefined?undefined:parseInt(entry.count,16);heapDump.addEntry(leafStackFrame,objectTypeName,size,count);}if(heapDump.entries.length>0)heapDumps[allocatorName]=heapDump;}if(Object.keys(heapDumps).length>0)processMemoryDump.heapDumps=heapDumps;},parseMemoryDumpLevelOfDetail_:function(levelsOfDetail,dumps,pid,dumpId){var rawLevelOfDetail=dumps.level_of_detail;var level;switch(rawLevelOfDetail){case'background':level=BACKGROUND;break;case'light':level=LIGHT;break;case'detailed':level=DETAILED;break;case undefined:level=undefined;break;default:this.model_.importWarning({type:'memory_dump_parse_error',message:'unknown raw level of detail \''+rawLevelOfDetail+'\' of process memory dump for PID='+pid+' and dump ID='+dumpId+'.'});return;}if(!this.updateMemoryDumpLevelOfDetail_(levelsOfDetail,'process',level)){this.model_.importWarning({type:'memory_dump_parse_error',message:'diffent levels of detail provided for process memory'+' dump for PID='+pid+' (dump ID='+dumpId+').'});}},updateMemoryDumpLevelOfDetail_:function(levelsOfDetail,scope,level){if(!(scope in levelsOfDetail)||level===levelsOfDetail[scope]){levelsOfDetail[scope]=level;return true;}if(MEMORY_DUMP_LEVEL_OF_DETAIL_ORDER.indexOf(level)>MEMORY_DUMP_LEVEL_OF_DETAIL_ORDER.indexOf(levelsOfDetail[scope])){levelsOfDetail[scope]=level;}return false;},parseMemoryDumpAllocatorDumps_:function(processMemoryDump,globalMemoryDump,processMemoryAllocatorDumpsByFullName,globalMemoryAllocatorDumpsByFullName,allMemoryAllocatorDumpsByGuid,dumps,pid,dumpId){var rawAllocatorDumps=dumps.allocators;if(rawAllocatorDumps===undefined)return;for(var fullName in rawAllocatorDumps){var rawAllocatorDump=rawAllocatorDumps[fullName];var guid=rawAllocatorDump.guid;if(guid===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump '+fullName+' for PID='+pid+' and dump ID='+dumpId+' does not have a GUID.'});}var flags=rawAllocatorDump.flags||0;var isWeakDump=!!(flags&WEAK_MEMORY_ALLOCATOR_DUMP_FLAG);var containerMemoryDump;var dstIndex;if(fullName.startsWith(GLOBAL_MEMORY_ALLOCATOR_DUMP_PREFIX)){fullName=fullName.substring(GLOBAL_MEMORY_ALLOCATOR_DUMP_PREFIX.length);containerMemoryDump=globalMemoryDump;dstIndex=globalMemoryAllocatorDumpsByFullName;}else{containerMemoryDump=processMemoryDump;dstIndex=processMemoryAllocatorDumpsByFullName;}var allocatorDump=allMemoryAllocatorDumpsByGuid[guid];if(allocatorDump===undefined){if(fullName in dstIndex){this.model_.importWarning({type:'memory_dump_parse_error',message:'Multiple GUIDs provided for'+' memory allocator dump '+fullName+': '+dstIndex[fullName].guid+', '+guid+' (ignored) for'+' PID='+pid+' and dump ID='+dumpId+'.'});continue;}allocatorDump=new tr.model.MemoryAllocatorDump(containerMemoryDump,fullName,guid);allocatorDump.weak=isWeakDump;dstIndex[fullName]=allocatorDump;if(guid!==undefined)allMemoryAllocatorDumpsByGuid[guid]=allocatorDump;}else{if(allocatorDump.containerMemoryDump!==containerMemoryDump){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump '+fullName+' (GUID='+guid+') for PID='+pid+' and dump ID='+dumpId+' dumped in different contexts.'});continue;}if(allocatorDump.fullName!==fullName){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump with GUID='+guid+' for PID='+pid+' and dump ID='+dumpId+' has multiple names: '+allocatorDump.fullName+', '+fullName+' (ignored).'});continue;}if(!isWeakDump){allocatorDump.weak=false;}}var attributes=rawAllocatorDump.attrs;if(attributes===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump '+fullName+' (GUID='+guid+') for PID='+pid+' and dump ID='+dumpId+' does not have attributes.'});attributes={};}for(var attrName in attributes){var attrArgs=attributes[attrName];var attrType=attrArgs.type;var attrValue=attrArgs.value;switch(attrType){case'scalar':if(attrName in allocatorDump.numerics){this.model_.importWarning({type:'memory_dump_parse_error',message:'Multiple values provided for scalar attribute '+attrName+' of memory allocator dump '+fullName+' (GUID='+guid+') for PID='+pid+' and dump ID='+dumpId+'.'});break;}var unit=attrArgs.units==='bytes'?tr.b.Unit.byName.sizeInBytes_smallerIsBetter:tr.b.Unit.byName.unitlessNumber_smallerIsBetter;var value=parseInt(attrValue,16);allocatorDump.addNumeric(attrName,new tr.v.ScalarNumeric(unit,value));break;case'string':if(attrName in allocatorDump.diagnostics){this.model_.importWarning({type:'memory_dump_parse_error',message:'Multiple values provided for string attribute '+attrName+' of memory allocator dump '+fullName+' (GUID='+guid+') for PID='+pid+' and dump ID='+dumpId+'.'});break;}allocatorDump.addDiagnostic(attrName,attrValue);break;default:this.model_.importWarning({type:'memory_dump_parse_error',message:'Unknown type provided for attribute '+attrName+' of memory allocator dump '+fullName+' (GUID='+guid+') for PID='+pid+' and dump ID='+dumpId+': '+attrType});break;}}}},inferMemoryAllocatorDumpTree_:function(memoryAllocatorDumpsByFullName){var rootAllocatorDumps=[];var fullNames=Object.keys(memoryAllocatorDumpsByFullName);fullNames.sort();for(var i=0;i<fullNames.length;i++){var fullName=fullNames[i];var allocatorDump=memoryAllocatorDumpsByFullName[fullName];while(true){var lastSlashIndex=fullName.lastIndexOf('/');if(lastSlashIndex===-1){rootAllocatorDumps.push(allocatorDump);break;}var parentFullName=fullName.substring(0,lastSlashIndex);var parentAllocatorDump=memoryAllocatorDumpsByFullName[parentFullName];var parentAlreadyExisted=true;if(parentAllocatorDump===undefined){parentAlreadyExisted=false;parentAllocatorDump=new tr.model.MemoryAllocatorDump(allocatorDump.containerMemoryDump,parentFullName);if(allocatorDump.weak!==false){parentAllocatorDump.weak=undefined;}memoryAllocatorDumpsByFullName[parentFullName]=parentAllocatorDump;}allocatorDump.parent=parentAllocatorDump;parentAllocatorDump.children.push(allocatorDump);if(parentAlreadyExisted){if(!allocatorDump.weak){while(parentAllocatorDump!==undefined&&parentAllocatorDump.weak===undefined){parentAllocatorDump.weak=false;parentAllocatorDump=parentAllocatorDump.parent;}}break;}fullName=parentFullName;allocatorDump=parentAllocatorDump;}}for(var fullName in memoryAllocatorDumpsByFullName){var allocatorDump=memoryAllocatorDumpsByFullName[fullName];if(allocatorDump.weak===undefined)allocatorDump.weak=true;}return rootAllocatorDumps;},parseMemoryDumpAllocatorEdges_:function(allMemoryAllocatorDumpsByGuid,dumpIdEvents,dumpId){for(var pid in dumpIdEvents){var processEvents=dumpIdEvents[pid];for(var i=0;i<processEvents.length;i++){var processEvent=processEvents[i];var dumps=processEvent.args.dumps;if(dumps===undefined)continue;var rawEdges=dumps.allocators_graph;if(rawEdges===undefined)continue;for(var j=0;j<rawEdges.length;j++){var rawEdge=rawEdges[j];var sourceGuid=rawEdge.source;var sourceDump=allMemoryAllocatorDumpsByGuid[sourceGuid];if(sourceDump===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Edge for PID='+pid+' and dump ID='+dumpId+' is missing source memory allocator dump (GUID='+sourceGuid+').'});continue;}var targetGuid=rawEdge.target;var targetDump=allMemoryAllocatorDumpsByGuid[targetGuid];if(targetDump===undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Edge for PID='+pid+' and dump ID='+dumpId+' is missing target memory allocator dump (GUID='+targetGuid+').'});continue;}var importance=rawEdge.importance;var edge=new tr.model.MemoryAllocatorDumpLink(sourceDump,targetDump,importance);switch(rawEdge.type){case'ownership':if(sourceDump.owns!==undefined){this.model_.importWarning({type:'memory_dump_parse_error',message:'Memory allocator dump '+sourceDump.fullName+' (GUID='+sourceGuid+') already owns a memory'+' allocator dump ('+sourceDump.owns.target.fullName+').'});}else{sourceDump.owns=edge;targetDump.ownedBy.push(edge);}break;case'retention':sourceDump.retains.push(edge);targetDump.retainedBy.push(edge);break;default:this.model_.importWarning({type:'memory_dump_parse_error',message:'Invalid edge type: '+rawEdge.type+' (PID='+pid+', dump ID='+dumpId+', source='+sourceGuid+', target='+targetGuid+', importance='+importance+').'});}}}}},toModelTimeFromUs_:function(ts){if(!this.toModelTime_){this.toModelTime_=this.model_.clockSyncManager.getModelTimeTransformer(this.clockDomainId_);}return this.toModelTime_(tr.b.Unit.timestampFromUs(ts));},maybeToModelTimeFromUs_:function(ts){if(ts===undefined)return undefined;return this.toModelTimeFromUs_(ts);}};tr.importer.Importer.register(TraceEventImporter);return{TraceEventImporter:TraceEventImporter};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/v8/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/v8/

Statements: 21.77% (54 / 248)      Branches: 0% (0 / 87)      Functions: 4.08% (2 / 49)      Lines: 100% (2 / 2)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/v8/
File Statements Branches Functions Lines
codemap.js 28.57% (34 / 119) 0% (0 / 39) 3.03% (1 / 33) 100% (1 / 1)
splaytree.js 15.5% (20 / 129) 0% (0 / 48) 6.25% (1 / 16) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/v8/codemap.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/v8/codemap.js

Statements: 28.57% (34 / 119)      Branches: 0% (0 / 39)      Functions: 3.03% (1 / 33)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./splaytree.js");'use strict';global.tr.exportTo('tr.e.importer.v8',function(){function CodeMap(){this.dynamics_=new tr.e.importer.v8.SplayTree();this.dynamicsNameGen_=new tr.e.importer.v8.CodeMap.NameGenerator();this.statics_=new tr.e.importer.v8.SplayTree();this.libraries_=new tr.e.importer.v8.SplayTree();this.pages_=[];}CodeMap.PAGE_ALIGNMENT=12;CodeMap.PAGE_SIZE=1<<CodeMap.PAGE_ALIGNMENT;CodeMap.prototype.addCode=function(start,codeEntry){this.deleteAllCoveredNodes_(this.dynamics_,start,start+codeEntry.size);this.dynamics_.insert(start,codeEntry);};CodeMap.prototype.moveCode=function(from,to){var removedNode=this.dynamics_.remove(from);this.deleteAllCoveredNodes_(this.dynamics_,to,to+removedNode.value.size);this.dynamics_.insert(to,removedNode.value);};CodeMap.prototype.deleteCode=function(start){var removedNode=this.dynamics_.remove(start);};CodeMap.prototype.addLibrary=function(start,codeEntry){this.markPages_(start,start+codeEntry.size);this.libraries_.insert(start,codeEntry);};CodeMap.prototype.addStaticCode=function(start,codeEntry){this.statics_.insert(start,codeEntry);};CodeMap.prototype.markPages_=function(start,end){for(var addr=start;addr<=end;addr+=CodeMap.PAGE_SIZE){this.pages_[addr>>>CodeMap.PAGE_ALIGNMENT]=1;}};CodeMap.prototype.deleteAllCoveredNodes_=function(tree,start,end){var toDelete=[];var addr=end-1;while(addr>=start){var node=tree.findGreatestLessThan(addr);if(!node)break;var start2=node.key,end2=start2+node.value.size;if(start2<end&&start<end2)toDelete.push(start2);addr=start2-1;}for(var i=0,l=toDelete.length;i<l;++i)tree.remove(toDelete[i]);};CodeMap.prototype.isAddressBelongsTo_=function(addr,node){return addr>=node.key&&addr<node.key+node.value.size;};CodeMap.prototype.findInTree_=function(tree,addr){var node=tree.findGreatestLessThan(addr);return node&&this.isAddressBelongsTo_(addr,node)?node.value:null;};CodeMap.prototype.findEntryInLibraries=function(addr){var pageAddr=addr>>>CodeMap.PAGE_ALIGNMENT;if(pageAddr in this.pages_)return this.findInTree_(this.libraries_,addr);return undefined;};CodeMap.prototype.findEntry=function(addr){var pageAddr=addr>>>CodeMap.PAGE_ALIGNMENT;if(pageAddr in this.pages_){return this.findInTree_(this.statics_,addr)||this.findInTree_(this.libraries_,addr);}var min=this.dynamics_.findMin();var max=this.dynamics_.findMax();if(max!=null&&addr<max.key+max.value.size&&addr>=min.key){var dynaEntry=this.findInTree_(this.dynamics_,addr);if(dynaEntry==null)return null;if(!dynaEntry.nameUpdated_){dynaEntry.name=this.dynamicsNameGen_.getName(dynaEntry.name);dynaEntry.nameUpdated_=true;}return dynaEntry;}return null;};CodeMap.prototype.findDynamicEntryByStartAddress=function(addr){var node=this.dynamics_.find(addr);return node?node.value:null;};CodeMap.prototype.getAllDynamicEntries=function(){return this.dynamics_.exportValues();};CodeMap.prototype.getAllDynamicEntriesWithAddresses=function(){return this.dynamics_.exportKeysAndValues();};CodeMap.prototype.getAllStaticEntries=function(){return this.statics_.exportValues();};CodeMap.prototype.getAllLibrariesEntries=function(){return this.libraries_.exportValues();};CodeMap.CodeState={COMPILED:0,OPTIMIZABLE:1,OPTIMIZED:2};CodeMap.CodeEntry=function(size,opt_name,opt_type){this.id=tr.b.GUID.allocateSimple();this.size=size;this.name_=opt_name||'';this.type=opt_type||'';this.nameUpdated_=false;};CodeMap.CodeEntry.prototype={__proto__:Object.prototype,get name(){return this.name_;},set name(value){this.name_=value;},toString:function(){this.name_+': '+this.size.toString(16);}};CodeMap.CodeEntry.TYPE={SHARED_LIB:'SHARED_LIB',CPP:'CPP'};CodeMap.DynamicFuncCodeEntry=function(size,type,func,state){CodeMap.CodeEntry.call(this,size,'',type);this.func=func;this.state=state;};CodeMap.DynamicFuncCodeEntry.STATE_PREFIX=['','~','*'];CodeMap.DynamicFuncCodeEntry.prototype={__proto__:CodeMap.CodeEntry.prototype,get name(){return CodeMap.DynamicFuncCodeEntry.STATE_PREFIX[this.state]+this.func.name;},set name(value){this.name_=value;},getRawName:function(){return this.func.getName();},isJSFunction:function(){return true;},toString:function(){return this.type+': '+this.name+': '+this.size.toString(16);}};CodeMap.FunctionEntry=function(name){CodeMap.CodeEntry.call(this,0,name);};CodeMap.FunctionEntry.prototype={__proto__:CodeMap.CodeEntry.prototype,get name(){var name=this.name_;if(name.length==0){name='<anonymous>';}else if(name.charAt(0)==' '){name='<anonymous>'+name;}return name;},set name(value){this.name_=value;}};CodeMap.NameGenerator=function(){this.knownNames_={};};CodeMap.NameGenerator.prototype.getName=function(name){if(!(name in this.knownNames_)){this.knownNames_[name]=0;return name;}var count=++this.knownNames_[name];return name+' {'+count+'}';};return{CodeMap:CodeMap};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/v8/splaytree.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/extras/importer/v8/splaytree.js

Statements: 15.5% (20 / 129)      Branches: 0% (0 / 48)      Functions: 6.25% (1 / 16)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../../base/base.js");'use strict';global.tr.exportTo('tr.e.importer.v8',function(){function SplayTree(){};SplayTree.prototype.root_=null;SplayTree.prototype.isEmpty=function(){return!this.root_;};SplayTree.prototype.insert=function(key,value){if(this.isEmpty()){this.root_=new SplayTree.Node(key,value);return;}this.splay_(key);if(this.root_.key==key){return;}var node=new SplayTree.Node(key,value);if(key>this.root_.key){node.left=this.root_;node.right=this.root_.right;this.root_.right=null;}else{node.right=this.root_;node.left=this.root_.left;this.root_.left=null;}this.root_=node;};SplayTree.prototype.remove=function(key){if(this.isEmpty()){throw Error('Key not found: '+key);}this.splay_(key);if(this.root_.key!=key){throw Error('Key not found: '+key);}var removed=this.root_;if(!this.root_.left){this.root_=this.root_.right;}else{var right=this.root_.right;this.root_=this.root_.left;this.splay_(key);this.root_.right=right;}return removed;};SplayTree.prototype.find=function(key){if(this.isEmpty()){return null;}this.splay_(key);return this.root_.key==key?this.root_:null;};SplayTree.prototype.findMin=function(){if(this.isEmpty()){return null;}var current=this.root_;while(current.left){current=current.left;}return current;};SplayTree.prototype.findMax=function(opt_startNode){if(this.isEmpty()){return null;}var current=opt_startNode||this.root_;while(current.right){current=current.right;}return current;};SplayTree.prototype.findGreatestLessThan=function(key){if(this.isEmpty()){return null;}this.splay_(key);if(this.root_.key<=key){return this.root_;}else if(this.root_.left){return this.findMax(this.root_.left);}else{return null;}};SplayTree.prototype.exportKeysAndValues=function(){var result=[];this.traverse_(function(node){result.push([node.key,node.value]);});return result;};SplayTree.prototype.exportValues=function(){var result=[];this.traverse_(function(node){result.push(node.value);});return result;};SplayTree.prototype.splay_=function(key){if(this.isEmpty()){return;}var dummy,left,right;dummy=left=right=new SplayTree.Node(null,null);var current=this.root_;while(true){if(key<current.key){if(!current.left){break;}if(key<current.left.key){var tmp=current.left;current.left=tmp.right;tmp.right=current;current=tmp;if(!current.left){break;}}right.left=current;right=current;current=current.left;}else if(key>current.key){if(!current.right){break;}if(key>current.right.key){var tmp=current.right;current.right=tmp.left;tmp.left=current;current=tmp;if(!current.right){break;}}left.right=current;left=current;current=current.right;}else{break;}}left.right=current.left;right.left=current.right;current.left=dummy.right;current.right=dummy.left;this.root_=current;};SplayTree.prototype.traverse_=function(f){var nodesToVisit=[this.root_];while(nodesToVisit.length>0){var node=nodesToVisit.shift();if(node==null){continue;}f(node);nodesToVisit.push(node.left);nodesToVisit.push(node.right);}};SplayTree.Node=function(key,value){this.key=key;this.value=value;};SplayTree.Node.prototype.left=null;SplayTree.Node.prototype.right=null;return{SplayTree:SplayTree};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/

Statements: 14.4% (159 / 1104)      Branches: 0% (0 / 365)      Functions: 4.89% (9 / 184)      Lines: 100% (9 / 9)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/
File Statements Branches Functions Lines
context_processor.js 7.06% (6 / 85) 0% (0 / 35) 6.25% (1 / 16) 100% (1 / 1)
empty_importer.js 56.25% (9 / 16) 0% (0 / 8) 25% (1 / 4) 100% (1 / 1)
find_input_expectations.js 12.59% (69 / 548) 0% (0 / 221) 1.72% (1 / 58) 100% (1 / 1)
find_load_expectations.js 29.17% (7 / 24) 0% (0 / 12) 50% (1 / 2) 100% (1 / 1)
find_startup_expectations.js 19.05% (8 / 42) 0% (0 / 12) 11.11% (1 / 9) 100% (1 / 1)
import.js 7.74% (13 / 168) 0% (0 / 22) 2% (1 / 50) 100% (1 / 1)
importer.js 60% (12 / 20) 0% (0 / 2) 9.09% (1 / 11) 100% (1 / 1)
proto_expectation.js 21.43% (15 / 70) 0% (0 / 18) 5.88% (1 / 17) 100% (1 / 1)
user_model_builder.js 15.27% (20 / 131) 0% (0 / 35) 5.88% (1 / 17) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/context_processor.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/context_processor.js

Statements: 7.06% (6 / 85)      Branches: 0% (0 / 35)      Functions: 6.25% (1 / 16)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.importer',function(){function ContextProcessor(model){this.model_=model;this.activeContexts_=[];this.stackPerType_={};this.contextCache_={};this.contextSetCache_={};this.cachedEntryForActiveContexts_=undefined;this.seenSnapshots_={};};ContextProcessor.prototype={enterContext:function(contextType,scopedId){var newActiveContexts=[this.getOrCreateContext_(contextType,scopedId)];for(var oldContext of this.activeContexts_){if(oldContext.type===contextType){this.pushContext_(oldContext);}else{newActiveContexts.push(oldContext);}}this.activeContexts_=newActiveContexts;this.cachedEntryForActiveContexts_=undefined;},leaveContext:function(contextType,scopedId){this.leaveContextImpl_(context=>context.type===contextType&&context.snapshot.scope===scopedId.scope&&context.snapshot.idRef===scopedId.id);},destroyContext:function(scopedId){tr.b.iterItems(this.stackPerType_,function(contextType,stack){var newLength=0;for(var i=0;i<stack.length;++i){if(stack[i].snapshot.scope!==scopedId.scope||stack[i].snapshot.idRef!==scopedId.id){stack[newLength++]=stack[i];}}stack.length=newLength;});this.leaveContextImpl_(context=>context.snapshot.scope===scopedId.scope&&context.snapshot.idRef===scopedId.id);},leaveContextImpl_:function(predicate){var newActiveContexts=[];for(var oldContext of this.activeContexts_){if(predicate(oldContext)){var previousContext=this.popContext_(oldContext.type);if(previousContext)newActiveContexts.push(previousContext);}else{newActiveContexts.push(oldContext);}}this.activeContexts_=newActiveContexts;this.cachedEntryForActiveContexts_=undefined;},getOrCreateContext_:function(contextType,scopedId){var context={type:contextType,snapshot:{scope:scopedId.scope,idRef:scopedId.id}};var key=this.getContextKey_(context);if(key in this.contextCache_)return this.contextCache_[key];this.contextCache_[key]=context;var snapshotKey=this.getSnapshotKey_(scopedId);this.seenSnapshots_[snapshotKey]=true;return context;},pushContext_:function(context){if(!(context.type in this.stackPerType_))this.stackPerType_[context.type]=[];this.stackPerType_[context.type].push(context);},popContext_:function(contextType){if(!(contextType in this.stackPerType_))return undefined;return this.stackPerType_[contextType].pop();},getContextKey_:function(context){return[context.type,context.snapshot.scope,context.snapshot.idRef].join('\x00');},getSnapshotKey_:function(scopedId){return[scopedId.scope,scopedId.idRef].join('\x00');},get activeContexts(){if(this.cachedEntryForActiveContexts_===undefined){var key=[];for(var context of this.activeContexts_)key.push(this.getContextKey_(context));key.sort();key=key.join('\x00');if(key in this.contextSetCache_){this.cachedEntryForActiveContexts_=this.contextSetCache_[key];}else{this.activeContexts_.sort(function(a,b){var keyA=this.getContextKey_(a);var keyB=this.getContextKey_(b);if(keyA<keyB)return-1;if(keyA>keyB)return 1;return 0;}.bind(this));this.contextSetCache_[key]=Object.freeze(this.activeContexts_);this.cachedEntryForActiveContexts_=this.contextSetCache_[key];}}return this.cachedEntryForActiveContexts_;},invalidateContextCacheForSnapshot:function(scopedId){var snapshotKey=this.getSnapshotKey_(scopedId);if(!(snapshotKey in this.seenSnapshots_))return;this.contextCache_={};this.contextSetCache_={};this.cachedEntryForActiveContexts_=undefined;this.activeContexts_=this.activeContexts_.map(function(context){if(context.snapshot.scope!==scopedId.scope||context.snapshot.idRef!==scopedId.id)return context;return{type:context.type,snapshot:{scope:context.snapshot.scope,idRef:context.snapshot.idRef}};});this.seenSnapshots_={};}};return{ContextProcessor:ContextProcessor};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/empty_importer.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/empty_importer.js

Statements: 56.25% (9 / 16)      Branches: 0% (0 / 8)      Functions: 25% (1 / 4)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");require("./importer.js");'use strict';global.tr.exportTo('tr.importer',function(){function EmptyImporter(events){this.importPriority=0;};EmptyImporter.canImport=function(eventData){if(eventData instanceof Array&&eventData.length==0)return true;if(typeof eventData==='string'||eventData instanceof String){return eventData.length==0;}return false;};EmptyImporter.prototype={__proto__:tr.importer.Importer.prototype,get importerName(){return'EmptyImporter';}};tr.importer.Importer.register(EmptyImporter);return{EmptyImporter:EmptyImporter};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/find_input_expectations.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/find_input_expectations.js

Statements: 12.59% (69 / 548)      Branches: 0% (0 / 221)      Functions: 1.72% (1 / 58)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/range_utils.js");require("../extras/chrome/cc/input_latency_async_slice.js");require("./proto_expectation.js");'use strict';global.tr.exportTo('tr.importer',function(){var ProtoExpectation=tr.importer.ProtoExpectation;var INPUT_TYPE=tr.e.cc.INPUT_EVENT_TYPE_NAMES;var KEYBOARD_TYPE_NAMES=[INPUT_TYPE.CHAR,INPUT_TYPE.KEY_DOWN_RAW,INPUT_TYPE.KEY_DOWN,INPUT_TYPE.KEY_UP];var MOUSE_RESPONSE_TYPE_NAMES=[INPUT_TYPE.CLICK,INPUT_TYPE.CONTEXT_MENU];var MOUSE_WHEEL_TYPE_NAMES=[INPUT_TYPE.MOUSE_WHEEL];var MOUSE_DRAG_TYPE_NAMES=[INPUT_TYPE.MOUSE_DOWN,INPUT_TYPE.MOUSE_MOVE,INPUT_TYPE.MOUSE_UP];var TAP_TYPE_NAMES=[INPUT_TYPE.TAP,INPUT_TYPE.TAP_CANCEL,INPUT_TYPE.TAP_DOWN];var PINCH_TYPE_NAMES=[INPUT_TYPE.PINCH_BEGIN,INPUT_TYPE.PINCH_END,INPUT_TYPE.PINCH_UPDATE];var FLING_TYPE_NAMES=[INPUT_TYPE.FLING_CANCEL,INPUT_TYPE.FLING_START];var TOUCH_TYPE_NAMES=[INPUT_TYPE.TOUCH_END,INPUT_TYPE.TOUCH_MOVE,INPUT_TYPE.TOUCH_START];var SCROLL_TYPE_NAMES=[INPUT_TYPE.SCROLL_BEGIN,INPUT_TYPE.SCROLL_END,INPUT_TYPE.SCROLL_UPDATE];var ALL_HANDLED_TYPE_NAMES=[].concat(KEYBOARD_TYPE_NAMES,MOUSE_RESPONSE_TYPE_NAMES,MOUSE_WHEEL_TYPE_NAMES,MOUSE_DRAG_TYPE_NAMES,PINCH_TYPE_NAMES,TAP_TYPE_NAMES,FLING_TYPE_NAMES,TOUCH_TYPE_NAMES,SCROLL_TYPE_NAMES);var RENDERER_FLING_TITLE='InputHandlerProxy::HandleGestureFling::started';var PLAYBACK_EVENT_TITLE='VideoPlayback';var CSS_ANIMATION_TITLE='Animation';var INPUT_MERGE_THRESHOLD_MS=200;var ANIMATION_MERGE_THRESHOLD_MS=32;var MOUSE_WHEEL_THRESHOLD_MS=40;var MOUSE_MOVE_THRESHOLD_MS=40;var KEYBOARD_IR_NAME='Keyboard';var MOUSE_IR_NAME='Mouse';var MOUSEWHEEL_IR_NAME='MouseWheel';var TAP_IR_NAME='Tap';var PINCH_IR_NAME='Pinch';var FLING_IR_NAME='Fling';var TOUCH_IR_NAME='Touch';var SCROLL_IR_NAME='Scroll';var CSS_IR_NAME='CSS';var WEBGL_IR_NAME='WebGL';var VIDEO_IR_NAME='Video';function compareEvents(x,y){if(x.start!==y.start)return x.start-y.start;if(x.end!==y.end)return x.end-y.end;if(x.guid&&y.guid)return x.guid-y.guid;return 0;}function forEventTypesIn(events,typeNames,cb,opt_this){events.forEach(function(event){if(typeNames.indexOf(event.typeName)>=0){cb.call(opt_this,event);}});}function causedFrame(event){return event.associatedEvents.some(x=>x.title===tr.model.helpers.IMPL_RENDERING_STATS);}function getSortedFrameEventsByProcess(modelHelper){var frameEventsByPid={};tr.b.iterItems(modelHelper.rendererHelpers,function(pid,rendererHelper){frameEventsByPid[pid]=rendererHelper.getFrameEventsInRange(tr.model.helpers.IMPL_FRAMETIME_TYPE,modelHelper.model.bounds);});return frameEventsByPid;}function getSortedInputEvents(modelHelper){var inputEvents=[];var browserProcess=modelHelper.browserHelper.process;var mainThread=browserProcess.findAtMostOneThreadNamed('CrBrowserMain');for(var slice of mainThread.asyncSliceGroup.getDescendantEvents()){if(!slice.isTopLevel)continue;if(!(slice instanceof tr.e.cc.InputLatencyAsyncSlice))continue;if(isNaN(slice.start)||isNaN(slice.duration)||isNaN(slice.end))continue;inputEvents.push(slice);}return inputEvents.sort(compareEvents);}function findProtoExpectations(modelHelper,sortedInputEvents){var protoExpectations=[];var handlers=[handleKeyboardEvents,handleMouseResponseEvents,handleMouseWheelEvents,handleMouseDragEvents,handleTapResponseEvents,handlePinchEvents,handleFlingEvents,handleTouchEvents,handleScrollEvents,handleCSSAnimations,handleWebGLAnimations,handleVideoAnimations];handlers.forEach(function(handler){protoExpectations.push.apply(protoExpectations,handler(modelHelper,sortedInputEvents));});protoExpectations.sort(compareEvents);return protoExpectations;}function handleKeyboardEvents(modelHelper,sortedInputEvents){var protoExpectations=[];forEventTypesIn(sortedInputEvents,KEYBOARD_TYPE_NAMES,function(event){var pe=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,KEYBOARD_IR_NAME);pe.pushEvent(event);protoExpectations.push(pe);});return protoExpectations;}function handleMouseResponseEvents(modelHelper,sortedInputEvents){var protoExpectations=[];forEventTypesIn(sortedInputEvents,MOUSE_RESPONSE_TYPE_NAMES,function(event){var pe=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,MOUSE_IR_NAME);pe.pushEvent(event);protoExpectations.push(pe);});return protoExpectations;}function handleMouseWheelEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;var prevEvent_=undefined;forEventTypesIn(sortedInputEvents,MOUSE_WHEEL_TYPE_NAMES,function(event){var prevEvent=prevEvent_;prevEvent_=event;if(currentPE&&prevEvent.start+MOUSE_WHEEL_THRESHOLD_MS>=event.start){if(currentPE.irType===ProtoExpectation.ANIMATION_TYPE){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,MOUSEWHEEL_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}return;}currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,MOUSEWHEEL_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);});return protoExpectations;}function handleMouseDragEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;var mouseDownEvent=undefined;forEventTypesIn(sortedInputEvents,MOUSE_DRAG_TYPE_NAMES,function(event){switch(event.typeName){case INPUT_TYPE.MOUSE_DOWN:if(causedFrame(event)){var pe=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,MOUSE_IR_NAME);pe.pushEvent(event);protoExpectations.push(pe);}else{mouseDownEvent=event;}break;case INPUT_TYPE.MOUSE_MOVE:if(!causedFrame(event)){var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);}else if(!currentPE||!currentPE.isNear(event,MOUSE_MOVE_THRESHOLD_MS)){currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,MOUSE_IR_NAME);currentPE.pushEvent(event);if(mouseDownEvent){currentPE.associatedEvents.push(mouseDownEvent);mouseDownEvent=undefined;}protoExpectations.push(currentPE);}else{if(currentPE.irType===ProtoExpectation.ANIMATION_TYPE){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,MOUSE_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}}break;case INPUT_TYPE.MOUSE_UP:if(!mouseDownEvent){var pe=new ProtoExpectation(causedFrame(event)?ProtoExpectation.RESPONSE_TYPE:ProtoExpectation.IGNORED_TYPE,MOUSE_IR_NAME);pe.pushEvent(event);protoExpectations.push(pe);break;}if(currentPE){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,MOUSE_IR_NAME);if(mouseDownEvent)currentPE.associatedEvents.push(mouseDownEvent);currentPE.pushEvent(event);protoExpectations.push(currentPE);}mouseDownEvent=undefined;currentPE=undefined;break;}});if(mouseDownEvent){currentPE=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);currentPE.pushEvent(mouseDownEvent);protoExpectations.push(currentPE);}return protoExpectations;}function handleTapResponseEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;forEventTypesIn(sortedInputEvents,TAP_TYPE_NAMES,function(event){switch(event.typeName){case INPUT_TYPE.TAP_DOWN:currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,TAP_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);break;case INPUT_TYPE.TAP:if(currentPE){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,TAP_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}currentPE=undefined;break;case INPUT_TYPE.TAP_CANCEL:if(!currentPE){var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);break;}if(currentPE.isNear(event,INPUT_MERGE_THRESHOLD_MS)){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,TAP_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}currentPE=undefined;break;}});return protoExpectations;}function handlePinchEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;var sawFirstUpdate=false;var modelBounds=modelHelper.model.bounds;forEventTypesIn(sortedInputEvents,PINCH_TYPE_NAMES,function(event){switch(event.typeName){case INPUT_TYPE.PINCH_BEGIN:if(currentPE&&currentPE.isNear(event,INPUT_MERGE_THRESHOLD_MS)){currentPE.pushEvent(event);break;}currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,PINCH_IR_NAME);currentPE.pushEvent(event);currentPE.isAnimationBegin=true;protoExpectations.push(currentPE);sawFirstUpdate=false;break;case INPUT_TYPE.PINCH_UPDATE:if(!currentPE||currentPE.irType===ProtoExpectation.RESPONSE_TYPE&&sawFirstUpdate||!currentPE.isNear(event,INPUT_MERGE_THRESHOLD_MS)){currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,PINCH_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}else{currentPE.pushEvent(event);sawFirstUpdate=true;}break;case INPUT_TYPE.PINCH_END:if(currentPE){currentPE.pushEvent(event);}else{var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);}currentPE=undefined;break;}});return protoExpectations;}function handleFlingEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;function isRendererFling(event){return event.title===RENDERER_FLING_TITLE;}var browserHelper=modelHelper.browserHelper;var flingEvents=browserHelper.getAllAsyncSlicesMatching(isRendererFling);forEventTypesIn(sortedInputEvents,FLING_TYPE_NAMES,function(event){flingEvents.push(event);});flingEvents.sort(compareEvents);flingEvents.forEach(function(event){if(event.title===RENDERER_FLING_TITLE){if(currentPE){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,FLING_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}return;}switch(event.typeName){case INPUT_TYPE.FLING_START:if(currentPE){console.error('Another FlingStart? File a bug with this trace!');currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,FLING_IR_NAME);currentPE.pushEvent(event);currentPE.end=0;protoExpectations.push(currentPE);}break;case INPUT_TYPE.FLING_CANCEL:if(currentPE){currentPE.pushEvent(event);currentPE.end=event.start;currentPE=undefined;}else{var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);}break;}});if(currentPE&&!currentPE.end)currentPE.end=modelHelper.model.bounds.max;return protoExpectations;}function handleTouchEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;var sawFirstMove=false;forEventTypesIn(sortedInputEvents,TOUCH_TYPE_NAMES,function(event){switch(event.typeName){case INPUT_TYPE.TOUCH_START:if(currentPE){currentPE.pushEvent(event);}else{currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,TOUCH_IR_NAME);currentPE.pushEvent(event);currentPE.isAnimationBegin=true;protoExpectations.push(currentPE);sawFirstMove=false;}break;case INPUT_TYPE.TOUCH_MOVE:if(!currentPE){currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,TOUCH_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);break;}if(sawFirstMove&&currentPE.irType===ProtoExpectation.RESPONSE_TYPE||!currentPE.isNear(event,INPUT_MERGE_THRESHOLD_MS)){var prevEnd=currentPE.end;currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,TOUCH_IR_NAME);currentPE.pushEvent(event);currentPE.start=prevEnd;protoExpectations.push(currentPE);}else{currentPE.pushEvent(event);sawFirstMove=true;}break;case INPUT_TYPE.TOUCH_END:if(!currentPE){var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);break;}if(currentPE.isNear(event,INPUT_MERGE_THRESHOLD_MS)){currentPE.pushEvent(event);}else{var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);}currentPE=undefined;break;}});return protoExpectations;}function handleScrollEvents(modelHelper,sortedInputEvents){var protoExpectations=[];var currentPE=undefined;var sawFirstUpdate=false;forEventTypesIn(sortedInputEvents,SCROLL_TYPE_NAMES,function(event){switch(event.typeName){case INPUT_TYPE.SCROLL_BEGIN:currentPE=new ProtoExpectation(ProtoExpectation.RESPONSE_TYPE,SCROLL_IR_NAME);currentPE.pushEvent(event);currentPE.isAnimationBegin=true;protoExpectations.push(currentPE);sawFirstUpdate=false;break;case INPUT_TYPE.SCROLL_UPDATE:if(currentPE){if(currentPE.isNear(event,INPUT_MERGE_THRESHOLD_MS)&&(currentPE.irType===ProtoExpectation.ANIMATION_TYPE||!sawFirstUpdate)){currentPE.pushEvent(event);sawFirstUpdate=true;}else{currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,SCROLL_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}}else{currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,SCROLL_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}break;case INPUT_TYPE.SCROLL_END:if(!currentPE){console.error('ScrollEnd without ScrollUpdate? '+'File a bug with this trace!');var pe=new ProtoExpectation(ProtoExpectation.IGNORED_TYPE);pe.pushEvent(event);protoExpectations.push(pe);break;}currentPE.pushEvent(event);break;}});return protoExpectations;}function handleVideoAnimations(modelHelper,sortedInputEvents){var events=[];for(var pid in modelHelper.rendererHelpers){for(var asyncSlice of modelHelper.rendererHelpers[pid].mainThread.asyncSliceGroup.slices){if(asyncSlice.title===PLAYBACK_EVENT_TITLE)events.push(asyncSlice);}}events.sort(tr.importer.compareEvents);var protoExpectations=[];for(var event of events){var currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,VIDEO_IR_NAME);currentPE.start=event.start;currentPE.end=event.end;currentPE.pushEvent(event);protoExpectations.push(currentPE);}return protoExpectations;}function handleCSSAnimations(modelHelper,sortedInputEvents){var animationEvents=modelHelper.browserHelper.getAllAsyncSlicesMatching(function(event){return event.title===CSS_ANIMATION_TITLE&&event.isTopLevel&&event.duration>0;});var animationRanges=[];function pushAnimationRange(start,end,animation){var range=tr.b.Range.fromExplicitRange(start,end);range.animation=animation;animationRanges.push(range);}animationEvents.forEach(function(animation){if(animation.subSlices.length===0){pushAnimationRange(animation.start,animation.end,animation);}else{var start=undefined;animation.subSlices.forEach(function(sub){if(sub.args.data.state==='running'&&start===undefined){start=sub.start;}else if(sub.args.data.state==='paused'||sub.args.data.state==='idle'||sub.args.data.state==='finished'){if(start===undefined){start=modelHelper.model.bounds.min;}pushAnimationRange(start,sub.start,animation);start=undefined;}});if(start!==undefined)pushAnimationRange(start,animation.end,animation);}});return animationRanges.map(function(range){var protoExpectation=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,CSS_IR_NAME);protoExpectation.start=range.min;protoExpectation.end=range.max;protoExpectation.associatedEvents.push(range.animation);return protoExpectation;});}function findWebGLEvents(modelHelper,mailboxEvents,animationEvents){for(var event of modelHelper.model.getDescendantEvents()){if(event.title==='DrawingBuffer::prepareMailbox')mailboxEvents.push(event);else if(event.title==='PageAnimator::serviceScriptedAnimations')animationEvents.push(event);}}function findMailboxEventsNearAnimationEvents(mailboxEvents,animationEvents){if(animationEvents.length===0)return[];mailboxEvents.sort(compareEvents);animationEvents.sort(compareEvents);var animationIterator=animationEvents[Symbol.iterator]();var animationEvent=animationIterator.next().value;var filteredEvents=[];for(var event of mailboxEvents){while(animationEvent&&animationEvent.start<event.start-ANIMATION_MERGE_THRESHOLD_MS)animationEvent=animationIterator.next().value;if(!animationEvent)break;if(animationEvent.start<event.start+ANIMATION_MERGE_THRESHOLD_MS)filteredEvents.push(event);}return filteredEvents;}function createProtoExpectationsFromMailboxEvents(mailboxEvents){var protoExpectations=[];var currentPE=undefined;for(var event of mailboxEvents){if(currentPE===undefined||!currentPE.isNear(event,ANIMATION_MERGE_THRESHOLD_MS)){currentPE=new ProtoExpectation(ProtoExpectation.ANIMATION_TYPE,WEBGL_IR_NAME);currentPE.pushEvent(event);protoExpectations.push(currentPE);}else{currentPE.pushEvent(event);}}return protoExpectations;}function handleWebGLAnimations(modelHelper,sortedInputEvents){var prepareMailboxEvents=[];var scriptedAnimationEvents=[];findWebGLEvents(modelHelper,prepareMailboxEvents,scriptedAnimationEvents);var webGLMailboxEvents=findMailboxEventsNearAnimationEvents(prepareMailboxEvents,scriptedAnimationEvents);return createProtoExpectationsFromMailboxEvents(webGLMailboxEvents);}function postProcessProtoExpectations(modelHelper,protoExpectations){protoExpectations=findFrameEventsForAnimations(modelHelper,protoExpectations);protoExpectations=mergeIntersectingResponses(protoExpectations);protoExpectations=mergeIntersectingAnimations(protoExpectations);protoExpectations=fixResponseAnimationStarts(protoExpectations);protoExpectations=fixTapResponseTouchAnimations(protoExpectations);return protoExpectations;}function mergeIntersectingResponses(protoExpectations){var newPEs=[];while(protoExpectations.length){var pe=protoExpectations.shift();newPEs.push(pe);if(pe.irType!==ProtoExpectation.RESPONSE_TYPE)continue;for(var i=0;i<protoExpectations.length;++i){var otherPE=protoExpectations[i];if(otherPE.irType!==pe.irType)continue;if(!otherPE.intersects(pe))continue;var typeNames=pe.associatedEvents.map(function(event){return event.typeName;});if(otherPE.containsTypeNames(typeNames))continue;pe.merge(otherPE);protoExpectations.splice(i,1);--i;}}return newPEs;}function mergeIntersectingAnimations(protoExpectations){var newPEs=[];while(protoExpectations.length){var pe=protoExpectations.shift();newPEs.push(pe);if(pe.irType!==ProtoExpectation.ANIMATION_TYPE)continue;var isCSS=pe.containsSliceTitle(CSS_ANIMATION_TITLE);var isFling=pe.containsTypeNames([INPUT_TYPE.FLING_START]);var isVideo=pe.containsTypeNames([VIDEO_IR_NAME]);for(var i=0;i<protoExpectations.length;++i){var otherPE=protoExpectations[i];if(otherPE.irType!==pe.irType)continue;if(isCSS!=otherPE.containsSliceTitle(CSS_ANIMATION_TITLE))continue;if(isCSS){if(!pe.isNear(otherPE,ANIMATION_MERGE_THRESHOLD_MS))continue;}else if(!otherPE.intersects(pe)){continue;}if(isFling!==otherPE.containsTypeNames([INPUT_TYPE.FLING_START]))continue;if(isVideo!==otherPE.containsTypeNames([VIDEO_IR_NAME]))continue;pe.merge(otherPE);protoExpectations.splice(i,1);--i;}}return newPEs;}function fixResponseAnimationStarts(protoExpectations){protoExpectations.forEach(function(ape){if(ape.irType!==ProtoExpectation.ANIMATION_TYPE)return;protoExpectations.forEach(function(rpe){if(rpe.irType!==ProtoExpectation.RESPONSE_TYPE)return;if(!ape.containsTimestampInclusive(rpe.end))return;if(ape.containsTimestampInclusive(rpe.start))return;ape.start=rpe.end;});});return protoExpectations;}function fixTapResponseTouchAnimations(protoExpectations){function isTapResponse(pe){return pe.irType===ProtoExpectation.RESPONSE_TYPE&&pe.containsTypeNames([INPUT_TYPE.TAP]);}function isTouchAnimation(pe){return pe.irType===ProtoExpectation.ANIMATION_TYPE&&pe.containsTypeNames([INPUT_TYPE.TOUCH_MOVE])&&!pe.containsTypeNames([INPUT_TYPE.SCROLL_UPDATE,INPUT_TYPE.PINCH_UPDATE]);}var newPEs=[];while(protoExpectations.length){var pe=protoExpectations.shift();newPEs.push(pe);var peIsTapResponse=isTapResponse(pe);var peIsTouchAnimation=isTouchAnimation(pe);if(!peIsTapResponse&&!peIsTouchAnimation)continue;for(var i=0;i<protoExpectations.length;++i){var otherPE=protoExpectations[i];if(!otherPE.intersects(pe))continue;if(peIsTapResponse&&!isTouchAnimation(otherPE))continue;if(peIsTouchAnimation&&!isTapResponse(otherPE))continue;pe.irType=ProtoExpectation.RESPONSE_TYPE;pe.merge(otherPE);protoExpectations.splice(i,1);--i;}}return newPEs;}function findFrameEventsForAnimations(modelHelper,protoExpectations){var newPEs=[];var frameEventsByPid=getSortedFrameEventsByProcess(modelHelper);for(var pe of protoExpectations){if(pe.irType!==ProtoExpectation.ANIMATION_TYPE){newPEs.push(pe);continue;}var frameEvents=[];for(var pid of Object.keys(modelHelper.rendererHelpers)){var range=tr.b.Range.fromExplicitRange(pe.start,pe.end);frameEvents.push.apply(frameEvents,range.filterArray(frameEventsByPid[pid],e=>e.start));}if(frameEvents.length===0&&!pe.names.has(WEBGL_IR_NAME)){pe.irType=ProtoExpectation.IGNORED_TYPE;newPEs.push(pe);continue;}pe.associatedEvents.addEventSet(frameEvents);newPEs.push(pe);}return newPEs;}function checkAllInputEventsHandled(sortedInputEvents,protoExpectations){var handledEvents=[];protoExpectations.forEach(function(protoExpectation){protoExpectation.associatedEvents.forEach(function(event){if(event.title===CSS_ANIMATION_TITLE&&event.subSlices.length>0)return;if(handledEvents.indexOf(event)>=0&&event.title!==tr.model.helpers.IMPL_RENDERING_STATS){console.error('double-handled event',event.typeName,parseInt(event.start),parseInt(event.end),protoExpectation);return;}handledEvents.push(event);});});sortedInputEvents.forEach(function(event){if(handledEvents.indexOf(event)<0){console.error('UNHANDLED INPUT EVENT!',event.typeName,parseInt(event.start),parseInt(event.end));}});}function findInputExpectations(modelHelper){var sortedInputEvents=getSortedInputEvents(modelHelper);var protoExpectations=findProtoExpectations(modelHelper,sortedInputEvents);protoExpectations=postProcessProtoExpectations(modelHelper,protoExpectations);checkAllInputEventsHandled(sortedInputEvents,protoExpectations);var irs=[];protoExpectations.forEach(function(protoExpectation){var ir=protoExpectation.createInteractionRecord(modelHelper.model);if(ir)irs.push(ir);});return irs;}return{findInputExpectations:findInputExpectations,compareEvents:compareEvents,CSS_ANIMATION_TITLE:CSS_ANIMATION_TITLE};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/find_load_expectations.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/find_load_expectations.js

Statements: 29.17% (7 / 24)      Branches: 0% (0 / 12)      Functions: 50% (1 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../model/user_model/load_expectation.js");'use strict';global.tr.exportTo('tr.importer',function(){var NAVIGATION_START='NavigationTiming navigationStart';var FIRST_CONTENTFUL_PAINT_TITLE='firstContentfulPaint';function findLoadExpectations(modelHelper){var events=[];for(var event of modelHelper.model.getDescendantEvents()){if(event.title===NAVIGATION_START||event.title===FIRST_CONTENTFUL_PAINT_TITLE)events.push(event);}events.sort(tr.importer.compareEvents);var loads=[];var startEvent=undefined;for(var event of events){if(event.title===NAVIGATION_START){startEvent=event;}else if(event.title===FIRST_CONTENTFUL_PAINT_TITLE){if(startEvent){loads.push(new tr.model.um.LoadExpectation(modelHelper.model,tr.model.um.LOAD_SUBTYPE_NAMES.SUCCESSFUL,startEvent.start,event.start-startEvent.start));startEvent=undefined;}}}if(startEvent){loads.push(new tr.model.um.LoadExpectation(modelHelper.model,tr.model.um.LOAD_SUBTYPE_NAMES.SUCCESSFUL,startEvent.start,modelHelper.model.bounds.max-startEvent.start));}return loads;}return{findLoadExpectations:findLoadExpectations};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/find_startup_expectations.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/find_startup_expectations.js

Statements: 19.05% (8 / 42)      Branches: 0% (0 / 12)      Functions: 11.11% (1 / 9)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../model/user_model/startup_expectation.js");'use strict';global.tr.exportTo('tr.importer',function(){function getAllFrameEvents(modelHelper){var frameEvents=[];frameEvents.push.apply(frameEvents,modelHelper.browserHelper.getFrameEventsInRange(tr.model.helpers.IMPL_FRAMETIME_TYPE,modelHelper.model.bounds));tr.b.iterItems(modelHelper.rendererHelpers,function(pid,renderer){frameEvents.push.apply(frameEvents,renderer.getFrameEventsInRange(tr.model.helpers.IMPL_FRAMETIME_TYPE,modelHelper.model.bounds));});return frameEvents.sort(tr.importer.compareEvents);}function getStartupEvents(modelHelper){function isStartupSlice(slice){return slice.title==='BrowserMainLoop::CreateThreads';}var events=modelHelper.browserHelper.getAllAsyncSlicesMatching(isStartupSlice);var deduper=new tr.model.EventSet();events.forEach(function(event){var sliceGroup=event.parentContainer.sliceGroup;var slice=sliceGroup&&sliceGroup.findFirstSlice();if(slice)deduper.push(slice);});return deduper.toArray();}function findStartupExpectations(modelHelper){var openingEvents=getStartupEvents(modelHelper);var closingEvents=getAllFrameEvents(modelHelper);var startups=[];openingEvents.forEach(function(openingEvent){closingEvents.forEach(function(closingEvent){if(openingEvent.closingEvent)return;if(closingEvent.openingEvent)return;if(closingEvent.start<=openingEvent.start)return;if(openingEvent.parentContainer.parent.pid!==closingEvent.parentContainer.parent.pid)return;openingEvent.closingEvent=closingEvent;closingEvent.openingEvent=openingEvent;var se=new tr.model.um.StartupExpectation(modelHelper.model,openingEvent.start,closingEvent.end-openingEvent.start);se.associatedEvents.push(openingEvent);se.associatedEvents.push(closingEvent);startups.push(se);});});return startups;}return{findStartupExpectations:findStartupExpectations};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/import.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/import.js

Statements: 7.74% (13 / 168)      Branches: 0% (0 / 22)      Functions: 2% (1 / 50)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");require("../base/timing.js");require("./empty_importer.js");require("./importer.js");require("./user_model_builder.js");require("../ui/base/overlay.js");'use strict';global.tr.exportTo('tr.importer',function(){var Timing=tr.b.Timing;function ImportOptions(){this.shiftWorldToZero=true;this.pruneEmptyContainers=true;this.showImportWarnings=true;this.trackDetailedModelStats=false;this.customizeModelCallback=undefined;var auditorTypes=tr.c.Auditor.getAllRegisteredTypeInfos();this.auditorConstructors=auditorTypes.map(function(typeInfo){return typeInfo.constructor;});}function Import(model,opt_options){if(model===undefined)throw new Error('Must provide model to import into.');this.importing_=false;this.importOptions_=opt_options||new ImportOptions();this.model_=model;this.model_.importOptions=this.importOptions_;}Import.prototype={__proto__:Object.prototype,importTraces:function(traces){var progressMeter={update:function(msg){}};tr.b.Task.RunSynchronously(this.createImportTracesTask(progressMeter,traces));},importTracesWithProgressDialog:function(traces){if(tr.isHeadless)throw new Error('Cannot use this method in headless mode.');var overlay=tr.ui.b.Overlay();overlay.title='Importing...';overlay.userCanClose=false;overlay.msgEl=document.createElement('div');Polymer.dom(overlay).appendChild(overlay.msgEl);overlay.msgEl.style.margin='20px';overlay.update=function(msg){Polymer.dom(this.msgEl).textContent=msg;};overlay.visible=true;var promise=tr.b.Task.RunWhenIdle(this.createImportTracesTask(overlay,traces));promise.then(function(){overlay.visible=false;},function(err){overlay.visible=false;});return promise;},createImportTracesTask:function(progressMeter,traces){if(this.importing_)throw new Error('Already importing.');this.importing_=true;var importTask=new tr.b.Task(function prepareImport(){progressMeter.update('I will now import your traces for you...');},this);var lastTask=importTask;var importers=[];lastTask=lastTask.timedAfter('TraceImport',function createImports(){traces=traces.slice(0);progressMeter.update('Creating importers...');for(var i=0;i<traces.length;++i)importers.push(this.createImporter_(traces[i]));for(var i=0;i<importers.length;i++){var subtraces=importers[i].extractSubtraces();for(var j=0;j<subtraces.length;j++){try{traces.push(subtraces[j]);importers.push(this.createImporter_(subtraces[j]));}catch(error){console.warn(error.name+': '+error.message);continue;}}}if(traces.length&&!this.hasEventDataDecoder_(importers)){throw new Error('Could not find an importer for the provided eventData.');}importers.sort(function(x,y){return x.importPriority-y.importPriority;});},this);lastTask=lastTask.timedAfter('TraceImport',function importClockSyncMarkers(task){importers.forEach(function(importer,index){task.subTask(Timing.wrapNamedFunction('TraceImport',importer.importerName,function runImportClockSyncMarkersOnOneImporter(){progressMeter.update('Importing clock sync markers '+(index+1)+' of '+importers.length);importer.importClockSyncMarkers();}),this);},this);},this);lastTask=lastTask.timedAfter('TraceImport',function runImport(task){importers.forEach(function(importer,index){task.subTask(Timing.wrapNamedFunction('TraceImport',importer.importerName,function runImportEventsOnOneImporter(){progressMeter.update('Importing '+(index+1)+' of '+importers.length);importer.importEvents();}),this);},this);},this);if(this.importOptions_.customizeModelCallback){lastTask=lastTask.timedAfter('TraceImport',function runCustomizeCallbacks(task){this.importOptions_.customizeModelCallback(this.model_);},this);}lastTask=lastTask.timedAfter('TraceImport',function importSampleData(task){importers.forEach(function(importer,index){progressMeter.update('Importing sample data '+(index+1)+'/'+importers.length);importer.importSampleData();},this);},this);lastTask=lastTask.timedAfter('TraceImport',function runAutoclosers(){progressMeter.update('Autoclosing open slices...');this.model_.autoCloseOpenSlices();this.model_.createSubSlices();},this);lastTask=lastTask.timedAfter('TraceImport',function finalizeImport(task){importers.forEach(function(importer,index){progressMeter.update('Finalizing import '+(index+1)+'/'+importers.length);importer.finalizeImport();},this);},this);lastTask=lastTask.timedAfter('TraceImport',function runPreinits(){progressMeter.update('Initializing objects (step 1/2)...');this.model_.preInitializeObjects();},this);if(this.importOptions_.pruneEmptyContainers){lastTask=lastTask.timedAfter('TraceImport',function runPruneEmptyContainers(){progressMeter.update('Pruning empty containers...');this.model_.pruneEmptyContainers();},this);}lastTask=lastTask.timedAfter('TraceImport',function runMergeKernelWithuserland(){progressMeter.update('Merging kernel with userland...');this.model_.mergeKernelWithUserland();},this);var auditors=[];lastTask=lastTask.timedAfter('TraceImport',function createAuditorsAndRunAnnotate(){progressMeter.update('Adding arbitrary data to model...');auditors=this.importOptions_.auditorConstructors.map(function(auditorConstructor){return new auditorConstructor(this.model_);},this);auditors.forEach(function(auditor){auditor.runAnnotate();auditor.installUserFriendlyCategoryDriverIfNeeded();});},this);lastTask=lastTask.timedAfter('TraceImport',function computeWorldBounds(){progressMeter.update('Computing final world bounds...');this.model_.computeWorldBounds(this.importOptions_.shiftWorldToZero);},this);lastTask=lastTask.timedAfter('TraceImport',function buildFlowEventIntervalTree(){progressMeter.update('Building flow event map...');this.model_.buildFlowEventIntervalTree();},this);lastTask=lastTask.timedAfter('TraceImport',function joinRefs(){progressMeter.update('Joining object refs...');this.model_.joinRefs();},this);lastTask=lastTask.timedAfter('TraceImport',function cleanupUndeletedObjects(){progressMeter.update('Cleaning up undeleted objects...');this.model_.cleanupUndeletedObjects();},this);lastTask=lastTask.timedAfter('TraceImport',function sortMemoryDumps(){progressMeter.update('Sorting memory dumps...');this.model_.sortMemoryDumps();},this);lastTask=lastTask.timedAfter('TraceImport',function finalizeMemoryGraphs(){progressMeter.update('Finalizing memory dump graphs...');this.model_.finalizeMemoryGraphs();},this);lastTask=lastTask.timedAfter('TraceImport',function initializeObjects(){progressMeter.update('Initializing objects (step 2/2)...');this.model_.initializeObjects();},this);lastTask=lastTask.timedAfter('TraceImport',function buildEventIndices(){progressMeter.update('Building event indices...');this.model_.buildEventIndices();},this);lastTask=lastTask.timedAfter('TraceImport',function buildUserModel(){progressMeter.update('Building UserModel...');var userModelBuilder=new tr.importer.UserModelBuilder(this.model_);userModelBuilder.buildUserModel();},this);lastTask=lastTask.timedAfter('TraceImport',function sortExpectations(){progressMeter.update('Sorting user expectations...');this.model_.userModel.sortExpectations();},this);lastTask=lastTask.timedAfter('TraceImport',function runAudits(){progressMeter.update('Running auditors...');auditors.forEach(function(auditor){auditor.runAudit();});},this);lastTask=lastTask.timedAfter('TraceImport',function sortAlerts(){progressMeter.update('Updating alerts...');this.model_.sortAlerts();},this);lastTask=lastTask.timedAfter('TraceImport',function lastUpdateBounds(){progressMeter.update('Update bounds...');this.model_.updateBounds();},this);lastTask=lastTask.timedAfter('TraceImport',function addModelWarnings(){progressMeter.update('Looking for warnings...');if(!this.model_.isTimeHighResolution){this.model_.importWarning({type:'low_resolution_timer',message:'Trace time is low resolution, trace may be unusable.',showToUser:true});}},this);lastTask.after(function(){this.importing_=false;},this);return importTask;},createImporter_:function(eventData){var importerConstructor=tr.importer.Importer.findImporterFor(eventData);if(!importerConstructor){throw new Error('Couldn\'t create an importer for the provided '+'eventData.');}return new importerConstructor(this.model_,eventData);},hasEventDataDecoder_:function(importers){for(var i=0;i<importers.length;++i){if(!importers[i].isTraceDataContainer())return true;}return false;}};return{ImportOptions:ImportOptions,Import:Import};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/importer.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/importer.js

Statements: 60% (12 / 20)      Branches: 0% (0 / 2)      Functions: 9.09% (1 / 11)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");require("../base/extension_registry.js");'use strict';global.tr.exportTo('tr.importer',function(){function Importer(){}Importer.prototype={__proto__:Object.prototype,get importerName(){return'Importer';},isTraceDataContainer:function(){return false;},extractSubtraces:function(){return[];},importClockSyncMarkers:function(){},importEvents:function(){},importSampleData:function(){},finalizeImport:function(){}};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.defaultMetadata={};options.mandatoryBaseClass=Importer;tr.b.decorateExtensionRegistry(Importer,options);Importer.findImporterFor=function(eventData){var typeInfo=Importer.findTypeInfoMatching(function(ti){return ti.constructor.canImport(eventData);});if(typeInfo)return typeInfo.constructor;return undefined;};return{Importer:Importer};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/proto_expectation.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/proto_expectation.js

Statements: 21.43% (15 / 70)      Branches: 0% (0 / 18)      Functions: 5.88% (1 / 17)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");require("../base/range_utils.js");require("../core/auditor.js");require("../model/event_info.js");require("../model/user_model/animation_expectation.js");require("../model/user_model/response_expectation.js");'use strict';global.tr.exportTo('tr.importer',function(){function ProtoExpectation(irType,name){this.irType=irType;this.names=new Set(name?[name]:undefined);this.start=Infinity;this.end=-Infinity;this.associatedEvents=new tr.model.EventSet();this.isAnimationBegin=false;}ProtoExpectation.RESPONSE_TYPE='r';ProtoExpectation.ANIMATION_TYPE='a';ProtoExpectation.IGNORED_TYPE='ignored';ProtoExpectation.prototype={get isValid(){return this.end>this.start;},containsTypeNames:function(typeNames){return this.associatedEvents.some(x=>typeNames.indexOf(x.typeName)>=0);},containsSliceTitle:function(title){return this.associatedEvents.some(x=>title===x.title);},createInteractionRecord:function(model){if(!this.isValid){console.error('Invalid ProtoExpectation: '+this.debug()+' File a bug with this trace!');return undefined;}var initiatorTitles=[];this.names.forEach(function(name){initiatorTitles.push(name);});initiatorTitles=initiatorTitles.sort().join(',');var duration=this.end-this.start;var ir=undefined;switch(this.irType){case ProtoExpectation.RESPONSE_TYPE:ir=new tr.model.um.ResponseExpectation(model,initiatorTitles,this.start,duration,this.isAnimationBegin);break;case ProtoExpectation.ANIMATION_TYPE:ir=new tr.model.um.AnimationExpectation(model,initiatorTitles,this.start,duration);break;}if(!ir)return undefined;ir.sourceEvents.addEventSet(this.associatedEvents);function pushAssociatedEvents(event){ir.associatedEvents.push(event);if(event.associatedEvents)ir.associatedEvents.addEventSet(event.associatedEvents);}this.associatedEvents.forEach(function(event){pushAssociatedEvents(event);if(event.subSlices)event.subSlices.forEach(pushAssociatedEvents);});return ir;},merge:function(other){other.names.forEach(function(name){this.names.add(name);}.bind(this));this.associatedEvents.addEventSet(other.associatedEvents);this.start=Math.min(this.start,other.start);this.end=Math.max(this.end,other.end);if(other.isAnimationBegin)this.isAnimationBegin=true;},pushEvent:function(event){this.start=Math.min(this.start,event.start);this.end=Math.max(this.end,event.end);this.associatedEvents.push(event);},containsTimestampInclusive:function(timestamp){return this.start<=timestamp&&timestamp<=this.end;},intersects:function(other){return other.start<this.end&&other.end>this.start;},isNear:function(event,threshold){return this.end+threshold>event.start;},debug:function(){var debugString=this.irType+'(';debugString+=parseInt(this.start)+' ';debugString+=parseInt(this.end);this.associatedEvents.forEach(function(event){debugString+=' '+event.typeName;});return debugString+')';}};return{ProtoExpectation:ProtoExpectation};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/user_model_builder.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/importer/user_model_builder.js

Statements: 15.27% (20 / 131)      Branches: 0% (0 / 35)      Functions: 5.88% (1 / 17)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");require("../base/range_utils.js");require("../core/auditor.js");require("../extras/chrome/cc/input_latency_async_slice.js");require("./find_input_expectations.js");require("./find_load_expectations.js");require("./find_startup_expectations.js");require("../model/event_info.js");require("../model/ir_coverage.js");require("../model/user_model/idle_expectation.js");'use strict';global.tr.exportTo('tr.importer',function(){var INSIGNIFICANT_MS=1;function UserModelBuilder(model){this.model=model;this.modelHelper=model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);};UserModelBuilder.supportsModelHelper=function(modelHelper){return modelHelper.browserHelper!==undefined;};UserModelBuilder.prototype={buildUserModel:function(){if(!this.modelHelper||!this.modelHelper.browserHelper)return;var expectations=undefined;try{expectations=this.findUserExpectations();}catch(error){this.model.importWarning({type:'UserModelBuilder',message:error,showToUser:true});return;}expectations.forEach(function(expectation){this.model.userModel.expectations.push(expectation);},this);},findUserExpectations:function(){var expectations=[];expectations.push.apply(expectations,tr.importer.findStartupExpectations(this.modelHelper));expectations.push.apply(expectations,tr.importer.findLoadExpectations(this.modelHelper));expectations.push.apply(expectations,tr.importer.findInputExpectations(this.modelHelper));expectations.push.apply(expectations,this.findIdleExpectations(expectations));this.collectUnassociatedEvents_(expectations);return expectations;},collectUnassociatedEvents_:function(rirs){var vacuumIRs=[];rirs.forEach(function(ir){if(ir instanceof tr.model.um.IdleExpectation||ir instanceof tr.model.um.LoadExpectation||ir instanceof tr.model.um.StartupExpectation)vacuumIRs.push(ir);});if(vacuumIRs.length===0)return;var allAssociatedEvents=tr.model.getAssociatedEvents(rirs);var unassociatedEvents=tr.model.getUnassociatedEvents(this.model,allAssociatedEvents);unassociatedEvents.forEach(function(event){if(!(event instanceof tr.model.ThreadSlice))return;if(!event.isTopLevel)return;for(var iri=0;iri<vacuumIRs.length;++iri){var ir=vacuumIRs[iri];if(event.start>=ir.start&&event.start<ir.end){ir.associatedEvents.addEventSet(event.entireHierarchy);return;}}});},findIdleExpectations:function(otherIRs){if(this.model.bounds.isEmpty)return;var emptyRanges=tr.b.findEmptyRangesBetweenRanges(tr.b.convertEventsToRanges(otherIRs),this.model.bounds);var irs=[];var model=this.model;emptyRanges.forEach(function(range){if(range.max<range.min+INSIGNIFICANT_MS)return;irs.push(new tr.model.um.IdleExpectation(model,range.min,range.max-range.min));});return irs;}};function createCustomizeModelLinesFromModel(model){var modelLines=[];modelLines.push('      audits.addEvent(model.browserMain,');modelLines.push('          {title: \'model start\', start: 0, end: 1});');var typeNames={};for(var typeName in tr.e.cc.INPUT_EVENT_TYPE_NAMES){typeNames[tr.e.cc.INPUT_EVENT_TYPE_NAMES[typeName]]=typeName;}var modelEvents=new tr.model.EventSet();model.userModel.expectations.forEach(function(ir,index){modelEvents.addEventSet(ir.sourceEvents);});modelEvents=modelEvents.toArray();modelEvents.sort(tr.importer.compareEvents);modelEvents.forEach(function(event){var startAndEnd='start: '+parseInt(event.start)+', '+'end: '+parseInt(event.end)+'});';if(event instanceof tr.e.cc.InputLatencyAsyncSlice){modelLines.push('      audits.addInputEvent(model, INPUT_TYPE.'+typeNames[event.typeName]+',');}else if(event.title==='RenderFrameImpl::didCommitProvisionalLoad'){modelLines.push('      audits.addCommitLoadEvent(model,');}else if(event.title==='InputHandlerProxy::HandleGestureFling::started'){modelLines.push('      audits.addFlingAnimationEvent(model,');}else if(event.title===tr.model.helpers.IMPL_RENDERING_STATS){modelLines.push('      audits.addFrameEvent(model,');}else if(event.title===tr.importer.CSS_ANIMATION_TITLE){modelLines.push('      audits.addEvent(model.rendererMain, {');modelLines.push('        title: \'Animation\', '+startAndEnd);return;}else{throw'You must extend createCustomizeModelLinesFromModel()'+'to support this event:\n'+event.title+'\n';}modelLines.push('          {'+startAndEnd);});modelLines.push('      audits.addEvent(model.browserMain,');modelLines.push('          {'+'title: \'model end\', '+'start: '+(parseInt(model.bounds.max)-1)+', '+'end: '+parseInt(model.bounds.max)+'});');return modelLines;}function createExpectedIRLinesFromModel(model){var expectedLines=[];var irCount=model.userModel.expectations.length;model.userModel.expectations.forEach(function(ir,index){var irString='      {';irString+='title: \''+ir.title+'\', ';irString+='start: '+parseInt(ir.start)+', ';irString+='end: '+parseInt(ir.end)+', ';irString+='eventCount: '+ir.sourceEvents.length;irString+='}';if(index<irCount-1)irString+=',';expectedLines.push(irString);});return expectedLines;}function createIRFinderTestCaseStringFromModel(model){var filename=window.location.hash.substr(1);var testName=filename.substr(filename.lastIndexOf('/')+1);testName=testName.substr(0,testName.indexOf('.'));try{var testLines=[];testLines.push('  /*');testLines.push('    This test was generated from');testLines.push('    '+filename+'');testLines.push('   */');testLines.push('  test(\''+testName+'\', function() {');testLines.push('    var verifier = new UserExpectationVerifier();');testLines.push('    verifier.customizeModelCallback = function(model) {');testLines.push.apply(testLines,createCustomizeModelLinesFromModel(model));testLines.push('    };');testLines.push('    verifier.expectedIRs = [');testLines.push.apply(testLines,createExpectedIRLinesFromModel(model));testLines.push('    ];');testLines.push('    verifier.verify();');testLines.push('  });');return testLines.join('\n');}catch(error){return error;}}return{UserModelBuilder:UserModelBuilder,createIRFinderTestCaseStringFromModel:createIRFinderTestCaseStringFromModel};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/

Statements: 29.28% (65 / 222)      Branches: 3.85% (2 / 52)      Functions: 27.27% (6 / 22)      Lines: 100% (5 / 5)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/
File Statements Branches Functions Lines
all_metrics.js 100% (15 / 15) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
cpu_process_metric.js 16.88% (13 / 77) 0% (0 / 22) 25% (2 / 8) 100% (1 / 1)
metric_registry.js 87.5% (14 / 16) 50% (2 / 4) 66.67% (2 / 3) 100% (1 / 1)
sample_metric.js 42.11% (8 / 19) 0% (0 / 8) 33.33% (1 / 3) 100% (1 / 1)
tracing_metric.js 15.79% (15 / 95) 0% (0 / 18) 12.5% (1 / 8) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/all_metrics.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/all_metrics.js

Statements: 100% (15 / 15)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./blink/gc_metric.js");require("./cpu_process_metric.js");require("./sample_metric.js");require("./system_health/clock_sync_latency_metric.js");require("./system_health/hazard_metric.js");require("./system_health/loading_metric.js");require("./system_health/memory_metric.js");require("./system_health/power_metric.js");require("./system_health/responsiveness_metric.js");require("./system_health/system_health_metrics.js");require("./system_health/webview_startup_metric.js");require("./tracing_metric.js");require("./v8/execution_metric.js");require("./v8/gc_metric.js");require("./v8/v8_metrics.js");
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/cpu_process_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/cpu_process_metric.js

Statements: 16.88% (13 / 77)      Branches: 0% (0 / 22)      Functions: 25% (2 / 8)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("./metric_registry.js");require("../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){function getCpuSnapshotsFromModel(model){var snapshots=[];for(var pid in model.processes){var snapshotInstances=model.processes[pid].objects.getAllInstancesNamed('CPUSnapshots');if(!snapshotInstances)continue;for(var object of snapshotInstances[0].snapshots)snapshots.push(object.args.processes);}return snapshots;}function getProcessSumsFromSnapshot(snapshot){var processSums=new Map();for(var processData of snapshot){var processName=processData.name;if(!processSums.has(processName))processSums.set(processName,{sum:0.0,paths:new Set()});processSums.get(processName).sum+=parseFloat(processData.pCpu);if(processData.path)processSums.get(processName).paths.add(processData.path);}return processSums;}function buildNumericsFromSnapshots(snapshots){var processNumerics=new Map();for(var snapshot of snapshots){var processSums=getProcessSumsFromSnapshot(snapshot);for(var _ref of processSums.entries()){var _ref2=_slicedToArray(_ref,2);var processName=_ref2[0];var processData=_ref2[1];if(!processNumerics.has(processName)){processNumerics.set(processName,{numeric:new tr.v.Histogram('cpu:percent:'+processName,tr.b.Unit.byName.normalizedPercentage_smallerIsBetter),paths:new Set()});}processNumerics.get(processName).numeric.addSample(processData.sum/100.0);for(var path of processData.paths)processNumerics.get(processName).paths.add(path);}}return processNumerics;}function cpuProcessMetric(values,model){var snapshots=getCpuSnapshotsFromModel(model);var processNumerics=buildNumericsFromSnapshots(snapshots);for(var _ref3 of processNumerics){var _ref4=_slicedToArray(_ref3,2);var processName=_ref4[0];var processData=_ref4[1];var numeric=processData.numeric;var missingSnapshotCount=snapshots.length-numeric.numValues;for(var i=0;i<missingSnapshotCount;i++)numeric.addSample(0);numeric.diagnostics.set('paths',new tr.v.d.Generic([...processData.paths]));values.addHistogram(numeric);}}tr.metrics.MetricRegistry.register(cpuProcessMetric);return{cpuProcessMetric:cpuProcessMetric};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/metric_registry.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/metric_registry.js

Statements: 87.5% (14 / 16)      Branches: 50% (2 / 4)      Functions: 66.67% (2 / 3)      Lines: 100% (1 / 1)      Ignored: none     

1 217  
"use strict";require("../base/base.js");require("../base/extension_registry.js");require("../base/iteration_helpers.js");'use strict';global.tr.exportTo('tr.metrics',function(){function MetricRegistry(){}var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.defaultMetadata={};tr.b.decorateExtensionRegistry(MetricRegistry,options);MetricRegistry.addEventListener('will-register',function(e){var metric=e.typeInfo.constructor;Iif(!(metric instanceof Function))throw new Error('Metrics must be functions');Iif(metric.length<2){throw new Error('Metrics take a ValueSet and a Model and '+'optionally an options dictionary');}});return{MetricRegistry:MetricRegistry};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/sample_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/sample_metric.js

Statements: 42.11% (8 / 19)      Branches: 0% (0 / 8)      Functions: 33.33% (1 / 3)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/range.js");require("./metric_registry.js");require("../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics',function(){function sampleMetric(values,model){var hist=new tr.v.Histogram('foo',tr.b.Unit.byName.sizeInBytes_smallerIsBetter);hist.addSample(9);hist.addSample(91,{bar:new tr.v.d.Generic({hello:42})});for(var expectation of model.userModel.expectations){if(expectation instanceof tr.model.um.ResponseExpectation){}else if(expectation instanceof tr.model.um.AnimationExpectation){}else if(expectation instanceof tr.model.um.IdleExpectation){}else if(expectation instanceof tr.model.um.LoadExpectation){}}var chromeHelper=model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);tr.b.iterItems(model.processes,function(pid,process){});values.addHistogram(hist);}tr.metrics.MetricRegistry.register(sampleMetric);return{sampleMetric:sampleMetric};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/tracing_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/tracing_metric.js

Statements: 15.79% (15 / 95)      Branches: 0% (0 / 18)      Functions: 12.5% (1 / 8)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/iteration_helpers.js");require("./metric_registry.js");require("../value/diagnostics/diagnostic_map.js");require("../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics',function(){var MEMORY_INFRA_TRACING_CATEGORY='disabled-by-default-memory-infra';var TIME_BOUNDARIES=tr.v.HistogramBinBoundaries.createExponential(1e-3,1e5,30);var BYTE_BOUNDARIES=tr.v.HistogramBinBoundaries.createExponential(1,1e9,30);var COUNT_BOUNDARIES=tr.v.HistogramBinBoundaries.createExponential(1,1e5,30);function addTimeDurationValue(valueName,duration,allValues){var hist=new tr.v.Histogram(valueName,tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,TIME_BOUNDARIES);hist.addSample(duration);allValues.addHistogram(hist);}function addMemoryInfraValues(values,model,categoryNamesToTotalEventSizes){var memoryDumpCount=model.globalMemoryDumps.length;if(memoryDumpCount===0)return;var totalOverhead=0;var nonMemoryInfraThreadOverhead=0;var overheadByProvider={};tr.b.iterItems(model.processes,function(pid,process){tr.b.iterItems(process.threads,function(tid,thread){tr.b.iterItems(thread.sliceGroup.slices,(unusedSliceId,slice)=>{if(slice.category!==MEMORY_INFRA_TRACING_CATEGORY)return;totalOverhead+=slice.duration;if(thread.name!=='MemoryInfra')nonMemoryInfraThreadOverhead+=slice.duration;if(slice.args&&slice.args['dump_provider.name']){var providerName=slice.args['dump_provider.name'];var durationAndCount=overheadByProvider[providerName];if(durationAndCount===undefined){overheadByProvider[providerName]=durationAndCount={duration:0,count:0};}durationAndCount.duration+=slice.duration;durationAndCount.count++;}});});});addTimeDurationValue('Average CPU overhead on all threads per memory-infra dump',totalOverhead/memoryDumpCount,values);addTimeDurationValue('Average CPU overhead on non-memory-infra threads per memory-infra '+'dump',nonMemoryInfraThreadOverhead/memoryDumpCount,values);tr.b.iterItems(overheadByProvider,function(providerName,overhead){addTimeDurationValue('Average CPU overhead of '+providerName+' per OnMemoryDump call',overhead.duration/overhead.count,values);});var memoryInfraEventsSize=categoryNamesToTotalEventSizes.get(MEMORY_INFRA_TRACING_CATEGORY);var memoryInfraTraceBytesValue=new tr.v.Histogram('Total trace size of memory-infra dumps in bytes',tr.b.Unit.byName.sizeInBytes_smallerIsBetter,BYTE_BOUNDARIES);memoryInfraTraceBytesValue.addSample(memoryInfraEventsSize);values.addHistogram(memoryInfraTraceBytesValue);var traceBytesPerDumpValue=new tr.v.Histogram('Average trace size of memory-infra dumps in bytes',tr.b.Unit.byName.sizeInBytes_smallerIsBetter,BYTE_BOUNDARIES);traceBytesPerDumpValue.addSample(memoryInfraEventsSize/memoryDumpCount);values.addHistogram(traceBytesPerDumpValue);}function tracingMetric(values,model){if(!model.stats.hasEventSizesinBytes){throw new Error('Model stats does not have event size information. '+'Please enable ImportOptions.trackDetailedModelStats.');}var eventStats=model.stats.allTraceEventStatsInTimeIntervals;eventStats.sort(function(a,b){return a.timeInterval-b.timeInterval;});var totalTraceBytes=eventStats.reduce((a,b)=>a+b.totalEventSizeinBytes,0);var maxEventCountPerSec=0;var maxEventBytesPerSec=0;var INTERVALS_PER_SEC=Math.floor(1000/model.stats.TIME_INTERVAL_SIZE_IN_MS);var runningEventNumPerSec=0;var runningEventBytesPerSec=0;var start=0;var end=0;while(end<eventStats.length){runningEventNumPerSec+=eventStats[end].numEvents;runningEventBytesPerSec+=eventStats[end].totalEventSizeinBytes;end++;while(eventStats[end-1].timeInterval-eventStats[start].timeInterval>=INTERVALS_PER_SEC){runningEventNumPerSec-=eventStats[start].numEvents;runningEventBytesPerSec-=eventStats[start].totalEventSizeinBytes;start++;}maxEventCountPerSec=Math.max(maxEventCountPerSec,runningEventNumPerSec);maxEventBytesPerSec=Math.max(maxEventBytesPerSec,runningEventBytesPerSec);}var stats=model.stats.allTraceEventStats;var categoryNamesToTotalEventSizes=stats.reduce((map,stat)=>map.set(stat.category,(map.get(stat.category)||0)+stat.totalEventSizeinBytes),new Map());var maxCatNameAndBytes=Array.from(categoryNamesToTotalEventSizes.entries()).reduce((a,b)=>b[1]>=a[1]?b:a);var maxEventBytesPerCategory=maxCatNameAndBytes[1];var categoryWithMaxEventBytes=maxCatNameAndBytes[0];var maxEventCountPerSecValue=new tr.v.Histogram('Max number of events per second',tr.b.Unit.byName.count_smallerIsBetter,COUNT_BOUNDARIES);maxEventCountPerSecValue.addSample(maxEventCountPerSec);var maxEventBytesPerSecValue=new tr.v.Histogram('Max event size in bytes per second',tr.b.Unit.byName.sizeInBytes_smallerIsBetter,BYTE_BOUNDARIES);maxEventBytesPerSecValue.addSample(maxEventBytesPerSec);var totalTraceBytesValue=new tr.v.Histogram('Total trace size in bytes',tr.b.Unit.byName.sizeInBytes_smallerIsBetter,BYTE_BOUNDARIES);totalTraceBytesValue.addSample(totalTraceBytes);var biggestCategory={name:categoryWithMaxEventBytes,size_in_bytes:maxEventBytesPerCategory};totalTraceBytesValue.diagnostics.set('category_with_max_event_size',new tr.v.d.Generic(biggestCategory));values.addHistogram(totalTraceBytesValue);maxEventCountPerSecValue.diagnostics.set('category_with_max_event_size',new tr.v.d.Generic(biggestCategory));values.addHistogram(maxEventCountPerSecValue);maxEventBytesPerSecValue.diagnostics.set('category_with_max_event_size',new tr.v.d.Generic(biggestCategory));values.addHistogram(maxEventBytesPerSecValue);addMemoryInfraValues(values,model,categoryNamesToTotalEventSizes);}tr.metrics.MetricRegistry.register(tracingMetric);return{tracingMetric:tracingMetric,MEMORY_INFRA_TRACING_CATEGORY:MEMORY_INFRA_TRACING_CATEGORY};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/blink/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/blink/

Statements: 30.38% (24 / 79)      Branches: 0% (0 / 6)      Functions: 5.26% (1 / 19)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/blink/
File Statements Branches Functions Lines
gc_metric.js 30.38% (24 / 79) 0% (0 / 6) 5.26% (1 / 19) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/blink/gc_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/blink/gc_metric.js

Statements: 30.38% (24 / 79)      Branches: 0% (0 / 6)      Functions: 5.26% (1 / 19)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/range.js");require("../../base/unit.js");require("../metric_registry.js");require("../v8/utils.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.blink',function(){var BLINK_GC_EVENTS={'BlinkGCMarking':'blink-gc-marking','ThreadState::completeSweep':'blink-gc-complete-sweep','ThreadState::performIdleLazySweep':'blink-gc-idle-lazy-sweep'};function isBlinkGarbageCollectionEvent(event){return event.title in BLINK_GC_EVENTS;}function blinkGarbageCollectionEventName(event){return BLINK_GC_EVENTS[event.title];}function blinkGcMetric(values,model){addDurationOfTopEvents(values,model);addTotalDurationOfTopEvents(values,model);addIdleTimesOfTopEvents(values,model);addTotalIdleTimesOfTopEvents(values,model);}tr.metrics.MetricRegistry.register(blinkGcMetric);var timeDurationInMs_smallerIsBetter=tr.b.Unit.byName.timeDurationInMs_smallerIsBetter;var percentage_biggerIsBetter=tr.b.Unit.byName.normalizedPercentage_biggerIsBetter;var CUSTOM_BOUNDARIES=tr.v.HistogramBinBoundaries.createLinear(0,20,200).addExponentialBins(200,100);function createNumericForTopEventTime(name){var n=new tr.v.Histogram(name,timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);n.customizeSummaryOptions({avg:true,count:true,max:true,min:false,std:true,sum:true,percentile:[0.90]});return n;}function createNumericForIdleTime(name){var n=new tr.v.Histogram(name,timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);n.customizeSummaryOptions({avg:true,count:false,max:true,min:false,std:false,sum:true,percentile:[]});return n;}function createPercentage(name,numerator,denominator){var histogram=new tr.v.Histogram(name,percentage_biggerIsBetter);if(denominator===0)histogram.addSample(0);else histogram.addSample(numerator/denominator);return histogram;}function addDurationOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isBlinkGarbageCollectionEvent,blinkGarbageCollectionEventName,function(name,events){var cpuDuration=createNumericForTopEventTime(name);events.forEach(function(event){cpuDuration.addSample(event.cpuDuration);});values.addHistogram(cpuDuration);});}function addTotalDurationOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isBlinkGarbageCollectionEvent,event=>'blink-gc-total',function(name,events){var cpuDuration=createNumericForTopEventTime(name);events.forEach(function(event){cpuDuration.addSample(event.cpuDuration);});values.addHistogram(cpuDuration);});}function addIdleTimesOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isBlinkGarbageCollectionEvent,blinkGarbageCollectionEventName,function(name,events){addIdleTimes(values,model,name,events);});}function addTotalIdleTimesOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isBlinkGarbageCollectionEvent,event=>'blink-gc-total',function(name,events){addIdleTimes(values,model,name,events);});}function addIdleTimes(values,model,name,events){var cpuDuration=createNumericForIdleTime(name+'_cpu');var insideIdle=createNumericForIdleTime(name+'_inside_idle');var outsideIdle=createNumericForIdleTime(name+'_outside_idle');var idleDeadlineOverrun=createNumericForIdleTime(name+'_idle_deadline_overrun');events.forEach(function(event){var idleTask=tr.metrics.v8.utils.findParent(event,tr.metrics.v8.utils.isIdleTask);var inside=0;var overrun=0;if(idleTask){var allottedTime=idleTask['args']['allotted_time_ms'];if(event.duration>allottedTime){overrun=event.duration-allottedTime;inside=event.cpuDuration*allottedTime/event.duration;}else{inside=event.cpuDuration;}}cpuDuration.addSample(event.cpuDuration);insideIdle.addSample(inside);outsideIdle.addSample(event.cpuDuration-inside);idleDeadlineOverrun.addSample(overrun);});values.addHistogram(idleDeadlineOverrun);values.addHistogram(outsideIdle);var percentage=createPercentage(name+'_percentage_idle',insideIdle.sum,cpuDuration.sum);values.addHistogram(percentage);}return{blinkGcMetric:blinkGcMetric};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/

Statements: 21.73% (196 / 902)      Branches: 0% (0 / 303)      Functions: 8.8% (11 / 125)      Lines: 100% (11 / 11)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/
File Statements Branches Functions Lines
clock_sync_latency_metric.js 36.67% (11 / 30) 0% (0 / 8) 25% (1 / 4) 100% (1 / 1)
cpu_time_metric.js 21.62% (8 / 37) 0% (0 / 10) 33.33% (1 / 3) 100% (1 / 1)
hazard_metric.js 45.16% (14 / 31) 0% (0 / 2) 12.5% (1 / 8) 100% (1 / 1)
loading_metric.js 16.43% (35 / 213) 0% (0 / 83) 5.56% (1 / 18) 100% (1 / 1)
long_tasks_metric.js 33.33% (13 / 39) 0% (0 / 12) 12.5% (1 / 8) 100% (1 / 1)
memory_metric.js 17.59% (57 / 324) 0% (0 / 125) 1.79% (1 / 56) 100% (1 / 1)
power_metric.js 19.27% (21 / 109) 0% (0 / 18) 8.33% (1 / 12) 100% (1 / 1)
responsiveness_metric.js 22.58% (14 / 62) 0% (0 / 33) 12.5% (1 / 8) 100% (1 / 1)
system_health_metrics.js 64.29% (9 / 14) 100% (0 / 0) 50% (1 / 2) 100% (1 / 1)
utils.js 42.86% (6 / 14) 0% (0 / 6) 25% (1 / 4) 100% (1 / 1)
webview_startup_metric.js 27.59% (8 / 29) 0% (0 / 6) 50% (1 / 2) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/clock_sync_latency_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/clock_sync_latency_metric.js

Statements: 36.67% (11 / 30)      Branches: 0% (0 / 8)      Functions: 25% (1 / 4)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../metric_registry.js");require("./utils.js");require("../../model/model.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){function syncIsComplete(markers){return markers.length===2;}function syncInvolvesTelemetry(markers){for(var marker of markers)if(marker.domainId===tr.model.ClockDomainId.TELEMETRY)return true;return false;}function clockSyncLatencyMetric(values,model){for(var markers of model.clockSyncManager.markersBySyncId.values()){var latency=undefined;var targetDomain=undefined;if(!syncIsComplete(markers)||!syncInvolvesTelemetry(markers))continue;for(var marker of markers){var domain=marker.domainId;if(domain===tr.model.ClockDomainId.TELEMETRY)latency=marker.endTs-marker.startTs;else targetDomain=domain.toLowerCase();}var hist=new tr.v.Histogram('clock_sync_latency_'+targetDomain,tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,tr.v.HistogramBinBoundaries.createExponential(1e-3,1e3,30));hist.description='Clock sync latency for domain '+targetDomain;hist.addSample(latency);values.addHistogram(hist);}}tr.metrics.MetricRegistry.register(clockSyncLatencyMetric);return{clockSyncLatencyMetric:clockSyncLatencyMetric};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/cpu_time_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/cpu_time_metric.js

Statements: 21.62% (8 / 37)      Branches: 0% (0 / 10)      Functions: 33.33% (1 / 3)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../metric_registry.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){var CPU_TIME_PERCENTAGE_BOUNDARIES=tr.v.HistogramBinBoundaries.createExponential(0.01,50,200);function cpuTimeMetric(values,model,opt_options){var rangeOfInterest=model.bounds;if(opt_options&&opt_options.rangeOfInterest)rangeOfInterest=opt_options.rangeOfInterest;var allProcessCpuTime=0;for(var pid in model.processes){var process=model.processes[pid];var processCpuTime=0;for(var tid in process.threads){var thread=process.threads[tid];var threadCpuTime=0;thread.sliceGroup.topLevelSlices.forEach(function(slice){if(slice.duration===0)return;if(!slice.cpuDuration)return;var sliceRange=tr.b.Range.fromExplicitRange(slice.start,slice.end);var intersection=rangeOfInterest.findIntersection(sliceRange);var fractionOfSliceInsideRangeOfInterest=intersection.duration/slice.duration;threadCpuTime+=slice.cpuDuration*fractionOfSliceInsideRangeOfInterest;});processCpuTime+=threadCpuTime;}allProcessCpuTime+=processCpuTime;}var normalizedAllProcessCpuTime=0;if(rangeOfInterest.duration>0){normalizedAllProcessCpuTime=allProcessCpuTime/rangeOfInterest.duration;}var unit=tr.b.Unit.byName.normalizedPercentage_smallerIsBetter;var cpuTimeHist=new tr.v.Histogram('cpu_time_percentage',unit,CPU_TIME_PERCENTAGE_BOUNDARIES);cpuTimeHist.description='Percent CPU utilization, normalized against a single core. Can be '+'greater than 100% if machine has multiple cores.';cpuTimeHist.addSample(normalizedAllProcessCpuTime);values.addHistogram(cpuTimeHist);}tr.metrics.MetricRegistry.register(cpuTimeMetric,{supportsRangeOfInterest:true});return{cpuTimeMetric:cpuTimeMetric};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/hazard_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/hazard_metric.js

Statements: 45.16% (14 / 31)      Branches: 0% (0 / 2)      Functions: 12.5% (1 / 8)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../metric_registry.js");require("./long_tasks_metric.js");require("../../value/numeric.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){var MS_PER_S=1000;var RESPONSE_RISK=tr.b.Statistics.LogNormalDistribution.fromMedianAndDiminishingReturns(100/MS_PER_S,50/MS_PER_S);function computeResponsivenessRisk(durationMs){durationMs+=16;return RESPONSE_RISK.computePercentile(durationMs/MS_PER_S);}function perceptualBlendSmallerIsBetter(hazardScore){return Math.exp(hazardScore);}function computeHazardForLongTasksInRangeOnThread(thread,opt_range){var taskHazardScores=[];tr.metrics.sh.iterateLongTopLevelTasksOnThreadInRange(thread,opt_range,function(task){taskHazardScores.push(computeResponsivenessRisk(task.duration));});return tr.b.Statistics.weightedMean(taskHazardScores,perceptualBlendSmallerIsBetter);}function computeHazardForLongTasks(model){var threadHazardScores=[];tr.metrics.sh.iterateRendererMainThreads(model,function(thread){threadHazardScores.push(computeHazardForLongTasksInRangeOnThread(thread));});return tr.b.Statistics.weightedMean(threadHazardScores,perceptualBlendSmallerIsBetter);}function hazardMetric(values,model){var overallHazard=computeHazardForLongTasks(model);if(overallHazard===undefined)overallHazard=0;var hist=new tr.v.Histogram('hazard',tr.b.Unit.byName.normalizedPercentage_smallerIsBetter);hist.addSample(overallHazard);values.addHistogram(hist);}tr.metrics.MetricRegistry.register(hazardMetric);return{hazardMetric:hazardMetric,computeHazardForLongTasksInRangeOnThread:computeHazardForLongTasksInRangeOnThread,computeHazardForLongTasks:computeHazardForLongTasks,computeResponsivenessRisk:computeResponsivenessRisk};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/loading_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/loading_metric.js

Statements: 16.43% (35 / 213)      Branches: 0% (0 / 83)      Functions: 5.56% (1 / 18)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/category_util.js");require("../../base/statistics.js");require("../metric_registry.js");require("./utils.js");require("../../model/helpers/chrome_model_helper.js");require("../../model/timed_event.js");require("../../value/histogram.js");require("../../value/numeric.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){var RESPONSIVENESS_THRESHOLD=50;var INTERACTIVE_WINDOW_SIZE=5*1000;var timeDurationInMs_smallerIsBetter=tr.b.Unit.byName.timeDurationInMs_smallerIsBetter;var RelatedEventSet=tr.v.d.RelatedEventSet;function hasCategoryAndName(event,category,title){return event.title===title&&event.category&&tr.b.getCategoryParts(event.category).indexOf(category)!==-1;}function findTargetRendererHelper(chromeHelper){var largestPid=-1;for(var pid in chromeHelper.rendererHelpers){var rendererHelper=chromeHelper.rendererHelpers[pid];if(rendererHelper.isChromeTracingUI)continue;if(pid>largestPid)largestPid=pid;}if(largestPid===-1)return undefined;return chromeHelper.rendererHelpers[largestPid];}function createBreakdownDiagnostic(rendererHelper,start,end){var breakdownDict=rendererHelper.generateTimeBreakdownTree(start,end);var breakdownDiagnostic=new tr.v.d.Breakdown();breakdownDiagnostic.colorScheme=tr.v.d.COLOR_SCHEME_CHROME_USER_FRIENDLY_CATEGORY_DRIVER;for(var label in breakdownDict){breakdownDiagnostic.set(label,breakdownDict[label].total);}return breakdownDiagnostic;}function NavigationStartFinder(rendererHelper){this.navigationStartsForFrameId_={};for(var ev of rendererHelper.mainThread.sliceGroup.childEvents()){if(!hasCategoryAndName(ev,'blink.user_timing','navigationStart'))continue;var frameIdRef=ev.args['frame'];var list=this.navigationStartsForFrameId_[frameIdRef];if(list===undefined)this.navigationStartsForFrameId_[frameIdRef]=list=[];list.unshift(ev);}}NavigationStartFinder.prototype={findNavigationStartEventForFrameBeforeTimestamp:function(frameIdRef,ts){var list=this.navigationStartsForFrameId_[frameIdRef];if(list===undefined){console.warn('No navigationStartEvent found for frame id "'+frameIdRef+'"');return undefined;}var eventBeforeTimestamp;for(var ev of list){if(ev.start>ts)continue;if(eventBeforeTimestamp===undefined)eventBeforeTimestamp=ev;}if(eventBeforeTimestamp===undefined){console.warn('Failed to find navigationStartEvent.');return undefined;}return eventBeforeTimestamp;}};var FIRST_PAINT_BOUNDARIES=tr.v.HistogramBinBoundaries.createLinear(0,1e3,20).addLinearBins(3e3,20).addExponentialBins(20e3,20);function createHistogram(name){var histogram=new tr.v.Histogram(name,timeDurationInMs_smallerIsBetter,FIRST_PAINT_BOUNDARIES);histogram.customizeSummaryOptions({avg:true,count:false,max:true,min:true,std:true,sum:false,percentile:[0.90,0.95,0.99]});return histogram;}function findFrameLoaderSnapshotAt(rendererHelper,frameIdRef,ts){var snapshot;var objects=rendererHelper.process.objects;var frameLoaderInstances=objects.instancesByTypeName_['FrameLoader'];if(frameLoaderInstances===undefined){console.warn('Failed to find FrameLoader for frameId "'+frameIdRef+'" at ts '+ts+', the trace maybe incomplete or from an old'+'Chrome.');return undefined;}var snapshot;for(var instance of frameLoaderInstances){if(!instance.isAliveAt(ts))continue;var maybeSnapshot=instance.getSnapshotAt(ts);if(frameIdRef!==maybeSnapshot.args['frame']['id_ref'])continue;snapshot=maybeSnapshot;}return snapshot;}function findAllUserTimingEvents(rendererHelper,title){var targetEvents=[];for(var ev of rendererHelper.process.getDescendantEvents()){if(!hasCategoryAndName(ev,'blink.user_timing',title))continue;targetEvents.push(ev);}return targetEvents;}function findFirstMeaningfulPaintCandidates(rendererHelper){var isTelemetryInternalEvent=prepareTelemetryInternalEventPredicate(rendererHelper);var candidatesForFrameId={};for(var ev of rendererHelper.process.getDescendantEvents()){if(!hasCategoryAndName(ev,'loading','firstMeaningfulPaintCandidate'))continue;if(isTelemetryInternalEvent(ev))continue;var frameIdRef=ev.args['frame'];if(frameIdRef===undefined)continue;var list=candidatesForFrameId[frameIdRef];if(list===undefined)candidatesForFrameId[frameIdRef]=list=[];list.push(ev);}return candidatesForFrameId;}function prepareTelemetryInternalEventPredicate(rendererHelper){var ignoreRegions=[];var internalRegionStart;for(var slice of rendererHelper.mainThread.asyncSliceGroup.getDescendantEvents()){if(!!slice.title.match(/^telemetry\.internal\.[^.]*\.start$/))internalRegionStart=slice.start;if(!!slice.title.match(/^telemetry\.internal\.[^.]*\.end$/)){var timedEvent=new tr.model.TimedEvent(internalRegionStart);timedEvent.duration=slice.end-internalRegionStart;ignoreRegions.push(timedEvent);}}return function isTelemetryInternalEvent(slice){for(var region of ignoreRegions)if(region.bounds(slice))return true;return false;};}var URL_BLACKLIST=['about:blank','data:text/html,pluginplaceholderdata'];function shouldIgnoreURL(url){return URL_BLACKLIST.indexOf(url)>=0;}var METRICS=[{valueName:'timeToFirstContentfulPaint',title:'firstContentfulPaint',description:'time to first contentful paint'},{valueName:'timeToOnload',title:'loadEventStart',description:'time to onload. '+'This is temporary metric used for PCv1/v2 sanity checking'}];function timeToFirstContentfulPaintMetric(values,model){var chromeHelper=model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);var rendererHelper=findTargetRendererHelper(chromeHelper);var isTelemetryInternalEvent=prepareTelemetryInternalEventPredicate(rendererHelper);var navigationStartFinder=new NavigationStartFinder(rendererHelper);for(var metric of METRICS){var histogram=createHistogram(metric.valueName);histogram.description=metric.description;var targetEvents=findAllUserTimingEvents(rendererHelper,metric.title);for(var ev of targetEvents){if(isTelemetryInternalEvent(ev))continue;var frameIdRef=ev.args['frame'];var snapshot=findFrameLoaderSnapshotAt(rendererHelper,frameIdRef,ev.start);if(snapshot===undefined||!snapshot.args.isLoadingMainFrame)continue;var url=snapshot.args.documentLoaderURL;if(shouldIgnoreURL(url))continue;var navigationStartEvent=navigationStartFinder.findNavigationStartEventForFrameBeforeTimestamp(frameIdRef,ev.start);if(navigationStartEvent===undefined)continue;var timeToEvent=ev.start-navigationStartEvent.start;histogram.addSample(timeToEvent,{url:new tr.v.d.Generic(url)});}values.addHistogram(histogram);}}function addTimeToInteractiveSampleToHistogram(histogram,rendererHelper,navigationStart,firstMeaningfulPaint,url){if(shouldIgnoreURL(url))return;var navigationStartTime=navigationStart.start;var firstInteractive=Infinity;var firstInteractiveCandidate=firstMeaningfulPaint;var lastLongTaskEvent=undefined;for(var ev of[...rendererHelper.mainThread.sliceGroup.childEvents()]){if(ev.start<firstInteractiveCandidate)continue;var interactiveDurationSoFar=ev.start-firstInteractiveCandidate;if(interactiveDurationSoFar>=INTERACTIVE_WINDOW_SIZE){firstInteractive=firstInteractiveCandidate;break;}if(ev.title==='TaskQueueManager::ProcessTaskFromWorkQueue'&&ev.duration>RESPONSIVENESS_THRESHOLD){firstInteractiveCandidate=ev.end-50;lastLongTaskEvent=ev;}}var breakdownDiagnostic=createBreakdownDiagnostic(rendererHelper,navigationStartTime,firstInteractive);var timeToFirstInteractive=firstInteractive-navigationStartTime;histogram.addSample(timeToFirstInteractive,{"Start":new RelatedEventSet(navigationStart),"Last long task":new RelatedEventSet(lastLongTaskEvent),"Navigation infos":new tr.v.d.Generic({url:url,pid:rendererHelper.pid,start:navigationStartTime,interactive:firstInteractive}),"Breakdown of [navStart, Interactive]":breakdownDiagnostic});}function timeToFirstMeaningfulPaintAndTimeToInteractiveMetrics(values,model){var chromeHelper=model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);var rendererHelper=findTargetRendererHelper(chromeHelper);var navigationStartFinder=new NavigationStartFinder(rendererHelper);var firstMeaningfulPaintHistogram=createHistogram('timeToFirstMeaningfulPaint');firstMeaningfulPaintHistogram.description='time to first meaningful paint';var firstInteractiveHistogram=createHistogram('timeToFirstInteractive');firstInteractiveHistogram.description='time to first interactive';function addFirstMeaningfulPaintSampleToHistogram(frameIdRef,navigationStart,fmpMarkerEvent){var snapshot=findFrameLoaderSnapshotAt(rendererHelper,frameIdRef,fmpMarkerEvent.start);if(snapshot===undefined||!snapshot.args.isLoadingMainFrame)return;var url=snapshot.args.documentLoaderURL;if(shouldIgnoreURL(url))return;var timeToFirstMeaningfulPaint=fmpMarkerEvent.start-navigationStart.start;var extraDiagnostic={url:url,pid:rendererHelper.pid};var breakdownDiagnostic=createBreakdownDiagnostic(rendererHelper,navigationStart.start,fmpMarkerEvent.start);firstMeaningfulPaintHistogram.addSample(timeToFirstMeaningfulPaint,{"Breakdown of [navStart, FMP]":breakdownDiagnostic,"Start":new RelatedEventSet(navigationStart),"End":new RelatedEventSet(fmpMarkerEvent),"Navigation infos":new tr.v.d.Generic({url:url,pid:rendererHelper.pid,start:navigationStart.start,fmp:fmpMarkerEvent.start})});return{firstMeaningfulPaint:fmpMarkerEvent.start,url:url};}var candidatesForFrameId=findFirstMeaningfulPaintCandidates(rendererHelper);for(var frameIdRef in candidatesForFrameId){var navigationStart;var lastCandidate;for(var ev of candidatesForFrameId[frameIdRef]){var navigationStartForThisCandidate=navigationStartFinder.findNavigationStartEventForFrameBeforeTimestamp(frameIdRef,ev.start);if(navigationStartForThisCandidate===undefined)continue;if(navigationStart!==navigationStartForThisCandidate){if(navigationStart!==undefined&&lastCandidate!==undefined){data=addFirstMeaningfulPaintSampleToHistogram(frameIdRef,navigationStart,lastCandidate);if(data!==undefined)addTimeToInteractiveSampleToHistogram(firstInteractiveHistogram,rendererHelper,navigationStart,data.firstMeaningfulPaint,data.url);}navigationStart=navigationStartForThisCandidate;}lastCandidate=ev;}if(lastCandidate!==undefined){var data=addFirstMeaningfulPaintSampleToHistogram(frameIdRef,navigationStart,lastCandidate);if(data!==undefined)addTimeToInteractiveSampleToHistogram(firstInteractiveHistogram,rendererHelper,navigationStart,data.firstMeaningfulPaint,data.url);}}values.addHistogram(firstMeaningfulPaintHistogram);values.addHistogram(firstInteractiveHistogram);}function loadingMetric(values,model){timeToFirstContentfulPaintMetric(values,model);timeToFirstMeaningfulPaintAndTimeToInteractiveMetrics(values,model);}tr.metrics.MetricRegistry.register(loadingMetric);return{loadingMetric:loadingMetric};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/long_tasks_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/long_tasks_metric.js

Statements: 33.33% (13 / 39)      Branches: 0% (0 / 12)      Functions: 12.5% (1 / 8)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../extras/chrome/chrome_user_friendly_category_driver.js");require("../metric_registry.js");require("../../model/helpers/chrome_model_helper.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){var LONG_TASK_MS=50;var LONGEST_TASK_MS=1000;function iterateLongTopLevelTasksOnThreadInRange(thread,opt_range,cb,opt_this){thread.sliceGroup.topLevelSlices.forEach(function(slice){if(opt_range&&!opt_range.intersectsExplicitRangeInclusive(slice.start,slice.end))return;if(slice.duration<LONG_TASK_MS)return;cb.call(opt_this,slice);});}function iterateRendererMainThreads(model,cb,opt_this){var modelHelper=model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);tr.b.dictionaryValues(modelHelper.rendererHelpers).forEach(function(rendererHelper){if(!rendererHelper.mainThread)return;cb.call(opt_this,rendererHelper.mainThread);});}function longTasksMetric(values,model,opt_options){var rangeOfInterest=opt_options?opt_options.rangeOfInterest:undefined;var longTaskHist=new tr.v.Histogram('long tasks',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,tr.v.HistogramBinBoundaries.createLinear(LONG_TASK_MS,LONGEST_TASK_MS,40));longTaskHist.description='durations of long tasks';var slices=new tr.model.EventSet();iterateRendererMainThreads(model,function(thread){iterateLongTopLevelTasksOnThreadInRange(thread,rangeOfInterest,function(task){longTaskHist.addSample(task.duration,{relatedEvents:new tr.v.d.RelatedEventSet([task])});slices.push(task);slices.addEventSet(task.descendentSlices);});});values.addHistogram(longTaskHist);var sampleForEvent=undefined;var breakdown=tr.v.d.RelatedHistogramBreakdown.buildFromEvents(values,'long tasks ',slices,e=>model.getUserFriendlyCategoryFromEvent(e)||'unknown',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,sampleForEvent,tr.v.HistogramBinBoundaries.createExponential(1,LONGEST_TASK_MS,40));breakdown.colorScheme=tr.v.d.COLOR_SCHEME_CHROME_USER_FRIENDLY_CATEGORY_DRIVER;longTaskHist.diagnostics.set('category',breakdown);}tr.metrics.MetricRegistry.register(longTasksMetric,{supportsRangeOfInterest:true});return{longTasksMetric:longTasksMetric,iterateLongTopLevelTasksOnThreadInRange:iterateLongTopLevelTasksOnThreadInRange,iterateRendererMainThreads:iterateRendererMainThreads,LONG_TASK_MS:LONG_TASK_MS,LONGEST_TASK_MS:LONGEST_TASK_MS};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/memory_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/memory_metric.js

Statements: 17.59% (57 / 324)      Branches: 0% (0 / 125)      Functions: 1.79% (1 / 56)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/iteration_helpers.js");require("../../base/multi_dimensional_view.js");require("../../base/range.js");require("../../base/unit.js");require("../metric_registry.js");require("../../model/container_memory_dump.js");require("../../model/helpers/chrome_model_helper.js");require("../../model/memory_allocator_dump.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){var BACKGROUND=tr.model.ContainerMemoryDump.LevelOfDetail.BACKGROUND;var LIGHT=tr.model.ContainerMemoryDump.LevelOfDetail.LIGHT;var DETAILED=tr.model.ContainerMemoryDump.LevelOfDetail.DETAILED;var sizeInBytes_smallerIsBetter=tr.b.Unit.byName.sizeInBytes_smallerIsBetter;var count_smallerIsBetter=tr.b.Unit.byName.count_smallerIsBetter;var DISPLAYED_SIZE_NUMERIC_NAME=tr.model.MemoryAllocatorDump.DISPLAYED_SIZE_NUMERIC_NAME;var LEVEL_OF_DETAIL_NAMES=new Map();LEVEL_OF_DETAIL_NAMES.set(BACKGROUND,'background');LEVEL_OF_DETAIL_NAMES.set(LIGHT,'light');LEVEL_OF_DETAIL_NAMES.set(DETAILED,'detailed');var BOUNDARIES_FOR_UNIT_MAP=new WeakMap();BOUNDARIES_FOR_UNIT_MAP.set(count_smallerIsBetter,tr.v.HistogramBinBoundaries.createLinear(0,20,20));BOUNDARIES_FOR_UNIT_MAP.set(sizeInBytes_smallerIsBetter,new tr.v.HistogramBinBoundaries(0).addBinBoundary(1024).addExponentialBins(16*1024*1024*1024,4*24));function memoryMetric(values,model,opt_options){var rangeOfInterest=opt_options?opt_options.rangeOfInterest:undefined;var browserNameToGlobalDumps=splitGlobalDumpsByBrowserName(model,rangeOfInterest);addGeneralMemoryDumpValues(browserNameToGlobalDumps,values);addDetailedMemoryDumpValues(browserNameToGlobalDumps,values);addMemoryDumpCountValues(browserNameToGlobalDumps,values);}function splitGlobalDumpsByBrowserName(model,opt_rangeOfInterest){var chromeModelHelper=model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);var browserNameToGlobalDumps=new Map();var globalDumpToBrowserHelper=new WeakMap();if(chromeModelHelper){chromeModelHelper.browserHelpers.forEach(function(helper){var globalDumps=skipDumpsThatDoNotIntersectRange(helper.process.memoryDumps.map(d=>d.globalMemoryDump),opt_rangeOfInterest);globalDumps.forEach(function(globalDump){var existingHelper=globalDumpToBrowserHelper.get(globalDump);if(existingHelper!==undefined){throw new Error('Memory dump ID clash across multiple browsers '+'with PIDs: '+existingHelper.pid+' and '+helper.pid);}globalDumpToBrowserHelper.set(globalDump,helper);});makeKeyUniqueAndSet(browserNameToGlobalDumps,canonicalizeName(helper.browserName),globalDumps);});}var unclassifiedGlobalDumps=skipDumpsThatDoNotIntersectRange(model.globalMemoryDumps.filter(g=>!globalDumpToBrowserHelper.has(g)),opt_rangeOfInterest);if(unclassifiedGlobalDumps.length>0){makeKeyUniqueAndSet(browserNameToGlobalDumps,'unknown_browser',unclassifiedGlobalDumps);}return browserNameToGlobalDumps;}function skipDumpsThatDoNotIntersectRange(dumps,opt_range){if(!opt_range)return dumps;return dumps.filter(d=>opt_range.intersectsExplicitRangeInclusive(d.start,d.end));}function canonicalizeName(name){return name.toLowerCase().replace(' ','_');}var USER_FRIENDLY_BROWSER_NAMES={'chrome':'Chrome','webview':'WebView','unknown_browser':'an unknown browser'};function convertBrowserNameToUserFriendlyName(browserName){for(var baseName in USER_FRIENDLY_BROWSER_NAMES){if(!browserName.startsWith(baseName))continue;var userFriendlyBaseName=USER_FRIENDLY_BROWSER_NAMES[baseName];var suffix=browserName.substring(baseName.length);if(suffix.length===0)return userFriendlyBaseName;else if(/^\d+$/.test(suffix))return userFriendlyBaseName+'('+suffix+')';}return'\''+browserName+'\' browser';}function canonicalizeProcessName(rawProcessName){if(!rawProcessName)return'unknown_processes';var baseCanonicalName=canonicalizeName(rawProcessName);switch(baseCanonicalName){case'renderer':return'renderer_processes';case'browser':return'browser_process';default:return baseCanonicalName;}}function convertProcessNameToUserFriendlyName(processName,opt_requirePlural){switch(processName){case'browser_process':return opt_requirePlural?'browser processes':'the browser process';case'renderer_processes':return'renderer processes';case'gpu_process':return opt_requirePlural?'GPU processes':'the GPU process';case'ppapi_process':return opt_requirePlural?'PPAPI processes':'the PPAPI process';case'all_processes':return'all processes';case'unknown_processes':return'unknown processes';default:return'\''+processName+'\' processes';}}function makeKeyUniqueAndSet(map,key,value){var uniqueKey=key;var nextIndex=2;while(map.has(uniqueKey)){uniqueKey=key+nextIndex;nextIndex++;}map.set(uniqueKey,value);}function addGeneralMemoryDumpValues(browserNameToGlobalDumps,values){addMemoryDumpValues(browserNameToGlobalDumps,gmd=>true,function(processDump,addProcessScalar){addProcessScalar({source:'process_count',value:1,unit:count_smallerIsBetter,descriptionPrefixBuilder:buildProcessCountDescriptionPrefix});if(processDump.totals!==undefined){tr.b.iterItems(SYSTEM_TOTAL_VALUE_PROPERTIES,function(propertyName,propertySpec){addProcessScalar({source:'reported_by_os',property:propertyName,component:['system_memory'],value:propertySpec.getPropertyFunction(processDump),unit:sizeInBytes_smallerIsBetter,descriptionPrefixBuilder:propertySpec.descriptionPrefixBuilder});});}if(processDump.memoryAllocatorDumps===undefined)return;processDump.memoryAllocatorDumps.forEach(function(rootAllocatorDump){tr.b.iterItems(CHROME_VALUE_PROPERTIES,function(propertyName,descriptionPrefixBuilder){addProcessScalar({source:'reported_by_chrome',component:[rootAllocatorDump.name],property:propertyName,value:rootAllocatorDump.numerics[propertyName],descriptionPrefixBuilder:descriptionPrefixBuilder});});if(rootAllocatorDump.numerics['allocated_objects_size']===undefined){var allocatedObjectsDump=rootAllocatorDump.getDescendantDumpByFullName('allocated_objects');if(allocatedObjectsDump!==undefined){addProcessScalar({source:'reported_by_chrome',component:[rootAllocatorDump.name],property:'allocated_objects_size',value:allocatedObjectsDump.numerics['size'],descriptionPrefixBuilder:CHROME_VALUE_PROPERTIES['allocated_objects_size']});}}});addV8MemoryDumpValues(processDump,addProcessScalar);},function(componentTree){var tracingNode=componentTree.children[1].get('tracing');if(tracingNode===undefined)return;for(var i=0;i<componentTree.values.length;i++)componentTree.values[i].total-=tracingNode.values[i].total;},values);}function addV8MemoryDumpValues(processDump,addProcessScalar){var v8Dump=processDump.getMemoryAllocatorDumpByFullName('v8');if(v8Dump===undefined)return;v8Dump.children.forEach(function(isolateDump){var mallocDump=isolateDump.getDescendantDumpByFullName('malloc');if(mallocDump!==undefined){addV8ComponentValues(mallocDump,['v8','allocated_by_malloc'],addProcessScalar);}var heapDump=isolateDump.getDescendantDumpByFullName('heap_spaces');if(heapDump!==undefined){addV8ComponentValues(heapDump,['v8','heap'],addProcessScalar);heapDump.children.forEach(function(spaceDump){if(spaceDump.name==='other_spaces')return;addV8ComponentValues(spaceDump,['v8','heap',spaceDump.name],addProcessScalar);});}});addProcessScalar({source:'reported_by_chrome',component:['v8'],property:'code_and_metadata_size',value:v8Dump.numerics['code_and_metadata_size'],descriptionPrefixBuilder:buildCodeAndMetadataSizeValueDescriptionPrefix});addProcessScalar({source:'reported_by_chrome',component:['v8'],property:'code_and_metadata_size',value:v8Dump.numerics['bytecode_and_metadata_size'],descriptionPrefixBuilder:buildCodeAndMetadataSizeValueDescriptionPrefix});}function addV8ComponentValues(componentDump,componentPath,addProcessScalar){tr.b.iterItems(CHROME_VALUE_PROPERTIES,function(propertyName,descriptionPrefixBuilder){addProcessScalar({source:'reported_by_chrome',component:componentPath,property:propertyName,value:componentDump.numerics[propertyName],descriptionPrefixBuilder:descriptionPrefixBuilder});});}function buildProcessCountDescriptionPrefix(componentPath,processName){if(componentPath.length>0){throw new Error('Unexpected process count non-empty component path: '+componentPath.join(':'));}return'total number of '+convertProcessNameToUserFriendlyName(processName,true);}function buildChromeValueDescriptionPrefix(formatSpec,componentPath,processName){var nameParts=[];if(componentPath.length===0){nameParts.push('total');if(formatSpec.totalUserFriendlyPropertyName){nameParts.push(formatSpec.totalUserFriendlyPropertyName);}else{if(formatSpec.userFriendlyPropertyNamePrefix)nameParts.push(formatSpec.userFriendlyPropertyNamePrefix);nameParts.push(formatSpec.userFriendlyPropertyName);}nameParts.push('reported by Chrome for');}else{if(formatSpec.componentPreposition===undefined){if(formatSpec.userFriendlyPropertyNamePrefix)nameParts.push(formatSpec.userFriendlyPropertyNamePrefix);nameParts.push(componentPath.join(':'));nameParts.push(formatSpec.userFriendlyPropertyName);}else{if(formatSpec.userFriendlyPropertyNamePrefix)nameParts.push(formatSpec.userFriendlyPropertyNamePrefix);nameParts.push(formatSpec.userFriendlyPropertyName);nameParts.push(formatSpec.componentPreposition);if(componentPath[componentPath.length-1]==='allocated_by_malloc'){nameParts.push('objects allocated by malloc for');nameParts.push(componentPath.slice(0,componentPath.length-1).join(':'));}else{nameParts.push(componentPath.join(':'));}}nameParts.push('in');}nameParts.push(convertProcessNameToUserFriendlyName(processName));return nameParts.join(' ');}var CHROME_VALUE_PROPERTIES={'effective_size':buildChromeValueDescriptionPrefix.bind(undefined,{userFriendlyPropertyName:'effective size',componentPreposition:'of'}),'allocated_objects_size':buildChromeValueDescriptionPrefix.bind(undefined,{userFriendlyPropertyName:'size of all objects allocated',totalUserFriendlyPropertyName:'size of all allocated objects',componentPreposition:'by'}),'locked_size':buildChromeValueDescriptionPrefix.bind(undefined,{userFriendlyPropertyName:'locked (pinned) size',componentPreposition:'of'}),'peak_size':buildChromeValueDescriptionPrefix.bind(undefined,{userFriendlyPropertyName:'peak size',componentPreposition:'of'})};var SYSTEM_TOTAL_VALUE_PROPERTIES={'resident_size':{getPropertyFunction:function(processDump){return processDump.totals.residentBytes;},descriptionPrefixBuilder:buildOsValueDescriptionPrefix.bind(undefined,'resident set size (RSS)')},'peak_resident_size':{getPropertyFunction:function(processDump){return processDump.totals.peakResidentBytes;},descriptionPrefixBuilder:buildOsValueDescriptionPrefix.bind(undefined,'peak resident set size')}};function addDetailedMemoryDumpValues(browserNameToGlobalDumps,values){addMemoryDumpValues(browserNameToGlobalDumps,g=>g.levelOfDetail===DETAILED,function(processDump,addProcessScalar){tr.b.iterItems(SYSTEM_VALUE_COMPONENTS,function(componentName,componentSpec){tr.b.iterItems(SYSTEM_VALUE_PROPERTIES,function(propertyName,propertySpec){var node=getDescendantVmRegionClassificationNode(processDump.vmRegions,componentSpec.classificationPath);var componentPath=['system_memory'];if(componentName)componentPath.push(componentName);addProcessScalar({source:'reported_by_os',component:componentPath,property:propertyName,value:node===undefined?0:node.byteStats[propertySpec.byteStat]||0,unit:sizeInBytes_smallerIsBetter,descriptionPrefixBuilder:propertySpec.descriptionPrefixBuilder});});});var memtrackDump=processDump.getMemoryAllocatorDumpByFullName('gpu/android_memtrack');if(memtrackDump!==undefined){var descriptionPrefixBuilder=SYSTEM_VALUE_PROPERTIES['proportional_resident_size'].descriptionPrefixBuilder;memtrackDump.children.forEach(function(memtrackChildDump){var childName=memtrackChildDump.name;addProcessScalar({source:'reported_by_os',component:['gpu_memory',childName],property:'proportional_resident_size',value:memtrackChildDump.numerics['memtrack_pss'],descriptionPrefixBuilder:descriptionPrefixBuilder});});}},function(componentTree){},values);}var SYSTEM_VALUE_COMPONENTS={'':{classificationPath:[]},'java_heap':{classificationPath:['Android','Java runtime','Spaces'],userFriendlyName:'the Java heap'},'ashmem':{classificationPath:['Android','Ashmem'],userFriendlyName:'ashmem'},'native_heap':{classificationPath:['Native heap'],userFriendlyName:'the native heap'}};var SYSTEM_VALUE_PROPERTIES={'proportional_resident_size':{byteStat:'proportionalResident',descriptionPrefixBuilder:buildOsValueDescriptionPrefix.bind(undefined,'proportional resident size (PSS)')},'private_dirty_size':{byteStat:'privateDirtyResident',descriptionPrefixBuilder:buildOsValueDescriptionPrefix.bind(undefined,'private dirty size')}};function buildOsValueDescriptionPrefix(userFriendlyPropertyName,componentPath,processName){if(componentPath.length>2){throw new Error('OS value component path for \''+userFriendlyPropertyName+'\' too long: '+componentPath.join(':'));}var nameParts=[];if(componentPath.length<2)nameParts.push('total');nameParts.push(userFriendlyPropertyName);if(componentPath.length>0){switch(componentPath[0]){case'system_memory':if(componentPath.length>1){var userFriendlyComponentName=SYSTEM_VALUE_COMPONENTS[componentPath[1]].userFriendlyName;if(userFriendlyComponentName===undefined){throw new Error('System value sub-component for \''+userFriendlyPropertyName+'\' unknown: '+componentPath.join(':'));}nameParts.push('of',userFriendlyComponentName,'in');}else{nameParts.push('of system memory (RAM) used by');}break;case'gpu_memory':if(componentPath.length>1){nameParts.push('of the',componentPath[1]);nameParts.push('Android memtrack component in');}else{nameParts.push('of GPU memory (Android memtrack) used by');}break;default:throw new Error('OS value component for \''+userFriendlyPropertyName+'\' unknown: '+componentPath.join(':'));}}else{nameParts.push('reported by the OS for');}nameParts.push(convertProcessNameToUserFriendlyName(processName));return nameParts.join(' ');}function buildCodeAndMetadataSizeValueDescriptionPrefix(componentPath,processName){return buildChromeValueDescriptionPrefix({userFriendlyPropertyNamePrefix:'size of',userFriendlyPropertyName:'code and metadata'},componentPath,processName);}function getDescendantVmRegionClassificationNode(node,path){for(var i=0;i<path.length;i++){if(node===undefined)break;node=tr.b.findFirstInArray(node.children,c=>c.title===path[i]);}return node;}function addMemoryDumpCountValues(browserNameToGlobalDumps,values){browserNameToGlobalDumps.forEach(function(globalDumps,browserName){var totalDumpCount=0;var levelOfDetailNameToDumpCount={};LEVEL_OF_DETAIL_NAMES.forEach(function(levelOfDetailName){levelOfDetailNameToDumpCount[levelOfDetailName]=0;});globalDumps.forEach(function(globalDump){totalDumpCount++;var levelOfDetailName=LEVEL_OF_DETAIL_NAMES.get(globalDump.levelOfDetail);if(!(levelOfDetailName in levelOfDetailNameToDumpCount))return;levelOfDetailNameToDumpCount[levelOfDetailName]++;});reportMemoryDumpCountAsValue(browserName,undefined,totalDumpCount,values);tr.b.iterItems(levelOfDetailNameToDumpCount,function(levelOfDetailName,levelOfDetailDumpCount){reportMemoryDumpCountAsValue(browserName,levelOfDetailName,levelOfDetailDumpCount,values);});});}function reportMemoryDumpCountAsValue(browserName,levelOfDetailName,levelOfDetailDumpCount,values){var nameParts=['memory',browserName,'all_processes','dump_count'];if(levelOfDetailName!==undefined)nameParts.push(levelOfDetailName);var name=nameParts.join(':');var histogram=new tr.v.Histogram(name,count_smallerIsBetter,BOUNDARIES_FOR_UNIT_MAP.get(count_smallerIsBetter));histogram.addSample(levelOfDetailDumpCount);histogram.description=['total number of',levelOfDetailName||'all','memory dumps added by',convertBrowserNameToUserFriendlyName(browserName),'to the trace'].join(' ');values.addHistogram(histogram);}function addMemoryDumpValues(browserNameToGlobalDumps,customGlobalDumpFilter,customProcessDumpValueExtractor,customComponentTreeModifier,values){browserNameToGlobalDumps.forEach(function(globalDumps,browserName){var filteredGlobalDumps=globalDumps.filter(customGlobalDumpFilter);var sourceToPropertyToData=extractDataFromGlobalDumps(filteredGlobalDumps,customProcessDumpValueExtractor);reportDataAsValues(sourceToPropertyToData,browserName,customComponentTreeModifier,values);});}function extractDataFromGlobalDumps(globalDumps,customProcessDumpValueExtractor){var sourceToPropertyToData=new Map();var dumpCount=globalDumps.length;globalDumps.forEach(function(globalDump,dumpIndex){tr.b.iterItems(globalDump.processMemoryDumps,function(_,processDump){extractDataFromProcessDump(processDump,sourceToPropertyToData,dumpIndex,dumpCount,customProcessDumpValueExtractor);});});return sourceToPropertyToData;}function extractDataFromProcessDump(processDump,sourceToPropertyToData,dumpIndex,dumpCount,customProcessDumpValueExtractor){var rawProcessName=processDump.process.name;var processNamePath=[canonicalizeProcessName(rawProcessName)];customProcessDumpValueExtractor(processDump,function addProcessScalar(spec){if(spec.value===undefined)return;var component=spec.component||[];function createDetailsForErrorMessage(){var propertyUserFriendlyName=spec.property===undefined?'(undefined)':spec.property;var componentUserFriendlyName=component.length===0?'(empty)':component.join(':');return['source=',spec.source,', property=',propertyUserFriendlyName,', component=',componentUserFriendlyName,' in ',processDump.process.userFriendlyName].join('');}var value,unit;if(spec.value instanceof tr.v.ScalarNumeric){value=spec.value.value;unit=spec.value.unit;if(spec.unit!==undefined){throw new Error('Histogram value for '+createDetailsForErrorMessage()+' already specifies a unit');}}else{value=spec.value;unit=spec.unit;}var propertyToData=sourceToPropertyToData.get(spec.source);if(propertyToData===undefined){propertyToData=new Map();sourceToPropertyToData.set(spec.source,propertyToData);}var data=propertyToData.get(spec.property);if(data===undefined){data={processAndComponentTreeBuilder:new tr.b.MultiDimensionalViewBuilder(2,dumpCount),unit:unit,descriptionPrefixBuilder:spec.descriptionPrefixBuilder};propertyToData.set(spec.property,data);}else if(data.unit!==unit){throw new Error('Multiple units provided for '+createDetailsForErrorMessage()+':'+data.unit.unitName+' and '+unit.unitName);}else if(data.descriptionPrefixBuilder!==spec.descriptionPrefixBuilder){throw new Error('Multiple description prefix builders provided for'+createDetailsForErrorMessage());}var values=new Array(dumpCount);values[dumpIndex]=value;data.processAndComponentTreeBuilder.addPath([processNamePath,component],values,tr.b.MultiDimensionalViewBuilder.ValueKind.TOTAL);});}function reportDataAsValues(sourceToPropertyToData,browserName,customComponentTreeModifier,values){sourceToPropertyToData.forEach(function(propertyToData,sourceName){propertyToData.forEach(function(data,propertyName){var tree=data.processAndComponentTreeBuilder.buildTopDownTreeView();var unit=data.unit;var descriptionPrefixBuilder=data.descriptionPrefixBuilder;customComponentTreeModifier(tree);reportComponentDataAsValues(browserName,sourceName,propertyName,'all_processes',[],tree,unit,descriptionPrefixBuilder,values);tree.children[0].forEach(function(processTree,processName){if(processTree.children[0].size>0){throw new Error('Multi-dimensional view node for source='+sourceName+', property='+(propertyName===undefined?'(undefined)':propertyName)+', process='+processName+' has children wrt the process name dimension');}customComponentTreeModifier(processTree);reportComponentDataAsValues(browserName,sourceName,propertyName,processName,[],processTree,unit,descriptionPrefixBuilder,values);});});});}function reportComponentDataAsValues(browserName,sourceName,propertyName,processName,componentPath,componentNode,unit,descriptionPrefixBuilder,values){var nameParts=['memory',browserName,processName,sourceName].concat(componentPath);if(propertyName!==undefined)nameParts.push(propertyName);var name=nameParts.join(':');var numeric=buildMemoryNumericFromNode(name,componentNode,unit);numeric.description=[descriptionPrefixBuilder(componentPath,processName),'in',convertBrowserNameToUserFriendlyName(browserName)].join(' ');values.addHistogram(numeric);var depth=componentPath.length;componentPath.push(undefined);componentNode.children[1].forEach(function(childNode,childName){componentPath[depth]=childName;reportComponentDataAsValues(browserName,sourceName,propertyName,processName,componentPath,childNode,unit,descriptionPrefixBuilder,values);});componentPath.pop();}function buildMemoryNumericFromNode(name,node,unit){var histogram=new tr.v.Histogram(name,unit,BOUNDARIES_FOR_UNIT_MAP.get(unit));node.values.forEach(v=>histogram.addSample(v.total));return histogram;}tr.metrics.MetricRegistry.register(memoryMetric,{supportsRangeOfInterest:true});return{memoryMetric:memoryMetric};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/power_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/power_metric.js

Statements: 19.27% (21 / 109)      Branches: 0% (0 / 18)      Functions: 8.33% (1 / 12)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/statistics.js");require("../metric_registry.js");require("./loading_metric.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){var FRAMES_PER_SEC=60;var FRAME_MS=tr.b.convertUnit(1.0/FRAMES_PER_SEC,tr.b.UnitScale.Metric.NONE,tr.b.UnitScale.Metric.MILLI);function getPowerData_(model,start,end){var durationInMs=end-start;var durationInS=tr.b.convertUnit(durationInMs,tr.b.UnitScale.Metric.MILLI,tr.b.UnitScale.Metric.NONE);var energyInJ=model.device.powerSeries.getEnergyConsumedInJ(start,end);var powerInW=energyInJ/durationInS;return{duration:durationInMs,energy:energyInJ,power:powerInW};}function getNavigationTTIIntervals_(model){var values=new tr.v.ValueSet();tr.metrics.sh.loadingMetric(values,model);var ttiValues=values.getValuesNamed('timeToFirstInteractive');var intervals=[];for(var bin of tr.b.getOnlyElement(ttiValues).allBins){for(var diagnostics of bin.diagnosticMaps){var breakdown=diagnostics.get('Navigation infos');intervals.push(tr.b.Range.fromExplicitRange(breakdown.value.start,breakdown.value.interactive));}}return intervals.sort((x,y)=>x.min-y.min);}function makeTimeHistogram_(values,title,description){var hist=new tr.v.Histogram(title+':time',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter);hist.customizeSummaryOptions({avg:false,count:false,max:true,min:true,std:false,sum:true});hist.description='Time spent in '+description;values.addHistogram(hist);return hist;}function makeEnergyHistogram_(values,title,description){var hist=new tr.v.Histogram(title+':energy',tr.b.Unit.byName.energyInJoules_smallerIsBetter);hist.customizeSummaryOptions({avg:false,count:false,max:true,min:true,std:false,sum:true});hist.description='Energy consumed in '+description;values.addHistogram(hist);return hist;}function makePowerHistogram_(values,title,description){var hist=new tr.v.Histogram(title+':power',tr.b.Unit.byName.powerInWatts_smallerIsBetter);hist.customizeSummaryOptions({avg:true,count:false,max:true,min:true,std:false,sum:false});hist.description='Energy consumption rate in '+description;values.addHistogram(hist);return hist;}function storePowerData_(data,timeHist,energyHist,powerHist){if(timeHist!==undefined)timeHist.addSample(data.duration);if(energyHist!==undefined)energyHist.addSample(data.energy);if(powerHist!==undefined)powerHist.addSample(data.power);}function createHistograms_(model,values){var hists={};hists.railStageToTimeHist=new Map();hists.railStageToEnergyHist=new Map();hists.railStageToPowerHist=new Map();hists.scrollTimeHist=makeTimeHistogram_(values,'scroll','scrolling');hists.scrollEnergyHist=makeEnergyHistogram_(values,'scroll','scrolling');hists.scrollPowerHist=makePowerHistogram_(values,'scroll','scrolling');hists.loadTimeHist=makeTimeHistogram_(values,'load','page loads');hists.loadEnergyHist=makeEnergyHistogram_(values,'load','page loads');hists.afterLoadTimeHist=makeTimeHistogram_(values,'after_load','period after load');hists.afterLoadPowerHist=makePowerHistogram_(values,'after_load','period after load');hists.videoPowerHist=makePowerHistogram_(values,'video','video playback');hists.frameEnergyHist=makeEnergyHistogram_(values,'per_frame','each frame');for(var exp of model.userModel.expectations){var currTitle=exp.title.toLowerCase().replace(' ','_');if(!hists.railStageToTimeHist.has(currTitle)){var timeHist=makeTimeHistogram_(values,currTitle,'RAIL stage '+currTitle);var energyHist=makeEnergyHistogram_(values,currTitle,'RAIL stage '+currTitle);var powerHist=makePowerHistogram_(values,currTitle,'RAIL stage '+currTitle);hists.railStageToTimeHist.set(currTitle,timeHist);hists.railStageToEnergyHist.set(currTitle,energyHist);hists.railStageToPowerHist.set(currTitle,powerHist);}}return hists;}function processInteractionRecord_(exp,model,hists){var currTitle=exp.title.toLowerCase().replace(' ','_');var data=getPowerData_(model,exp.start,exp.end);storePowerData_(data,hists.railStageToTimeHist.get(currTitle),hists.railStageToEnergyHist.get(currTitle),hists.railStageToPowerHist.get(currTitle));if(exp.title.indexOf("Scroll")!==-1){storePowerData_(data,hists.scrollTimeHist,hists.scrollEnergyHist,hists.scrollPowerHist);}if(exp.title.indexOf("Video")!==-1)storePowerData_(data,undefined,undefined,hists.videoPowerHist);}function computeLoadingMetric_(model,hists){var intervals=getNavigationTTIIntervals_(model);var lastLoadTime=undefined;for(var interval of intervals){var loadData=getPowerData_(model,interval.min,interval.max);storePowerData_(loadData,hists.loadTimeHist,hists.loadEnergyHist,undefined);lastLoadTime=lastLoadTime==undefined?interval.max:Math.max(lastLoadTime,interval.max);}if(lastLoadTime!==undefined){var afterLoadData=getPowerData_(model,lastLoadTime,model.bounds.max);storePowerData_(afterLoadData,hists.afterLoadTimeHist,undefined,hists.afterLoadPowerHist);}}function computeFrameBasedPowerMetric_(model,hists){model.device.powerSeries.updateBounds();var currentTime=model.device.powerSeries.bounds.min;while(currentTime<model.device.powerSeries.bounds.max){var frameData=getPowerData_(model,currentTime,currentTime+FRAME_MS);hists.frameEnergyHist.addSample(frameData.energy);currentTime+=FRAME_MS;}}function powerMetric(values,model){if(!model.device.powerSeries)return;var hists=createHistograms_(model,values);for(var exp of model.userModel.expectations)processInteractionRecord_(exp,model,hists);computeLoadingMetric_(model,hists);computeFrameBasedPowerMetric_(model,hists);}tr.metrics.MetricRegistry.register(powerMetric);return{powerMetric:powerMetric};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/responsiveness_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/responsiveness_metric.js

Statements: 22.58% (14 / 62)      Branches: 0% (0 / 33)      Functions: 12.5% (1 / 8)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/statistics.js");require("../metric_registry.js");require("./utils.js");require("../../model/user_model/animation_expectation.js");require("../../model/user_model/load_expectation.js");require("../../model/user_model/response_expectation.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){function computeAnimationThroughput(animationExpectation){if(animationExpectation.frameEvents===undefined||animationExpectation.frameEvents.length===0)throw new Error('Animation missing frameEvents '+animationExpectation.stableId);var durationInS=tr.b.convertUnit(animationExpectation.duration,tr.b.UnitScale.Metric.MILLI,tr.b.UnitScale.Metric.NONE);return animationExpectation.frameEvents.length/durationInS;}function computeAnimationframeTimeDiscrepancy(animationExpectation){if(animationExpectation.frameEvents===undefined||animationExpectation.frameEvents.length===0)throw new Error('Animation missing frameEvents '+animationExpectation.stableId);var frameTimestamps=animationExpectation.frameEvents;frameTimestamps=frameTimestamps.toArray().map(function(event){return event.start;});var absolute=true;return tr.b.Statistics.timestampsDiscrepancy(frameTimestamps,absolute);}function responsivenessMetric(values,model,opt_options){var responseNumeric=new tr.v.Histogram('response latency',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,tr.v.HistogramBinBoundaries.createLinear(100,1e3,50));var throughputNumeric=new tr.v.Histogram('animation throughput',tr.b.Unit.byName.unitlessNumber_biggerIsBetter,tr.v.HistogramBinBoundaries.createLinear(10,60,10));var frameTimeDiscrepancyNumeric=new tr.v.Histogram('animation frameTimeDiscrepancy',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,tr.v.HistogramBinBoundaries.createLinear(0,1e3,50).addExponentialBins(1e4,10));var latencyNumeric=new tr.v.Histogram('animation latency',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,tr.v.HistogramBinBoundaries.createLinear(0,300,60));model.userModel.expectations.forEach(function(ue){if(opt_options&&opt_options.rangeOfInterest&&!opt_options.rangeOfInterest.intersectsExplicitRangeInclusive(ue.start,ue.end))return;var sampleDiagnosticMap=tr.v.d.DiagnosticMap.fromObject({relatedEvents:new tr.v.d.RelatedEventSet([ue])});if(ue instanceof tr.model.um.IdleExpectation){return;}else if(ue instanceof tr.model.um.StartupExpectation){return;}else if(ue instanceof tr.model.um.LoadExpectation){}else if(ue instanceof tr.model.um.ResponseExpectation){responseNumeric.addSample(ue.duration,sampleDiagnosticMap);}else if(ue instanceof tr.model.um.AnimationExpectation){if(ue.frameEvents===undefined||ue.frameEvents.length===0){return;}var throughput=computeAnimationThroughput(ue);if(throughput===undefined)throw new Error('Missing throughput for '+ue.stableId);throughputNumeric.addSample(throughput,sampleDiagnosticMap);var frameTimeDiscrepancy=computeAnimationframeTimeDiscrepancy(ue);if(frameTimeDiscrepancy===undefined)throw new Error('Missing frameTimeDiscrepancy for '+ue.stableId);frameTimeDiscrepancyNumeric.addSample(frameTimeDiscrepancy,sampleDiagnosticMap);ue.associatedEvents.forEach(function(event){if(!(event instanceof tr.e.cc.InputLatencyAsyncSlice))return;latencyNumeric.addSample(event.duration,sampleDiagnosticMap);});}else{throw new Error('Unrecognized stage for '+ue.stableId);}});[responseNumeric,throughputNumeric,frameTimeDiscrepancyNumeric,latencyNumeric].forEach(function(numeric){numeric.customizeSummaryOptions({avg:true,max:true,min:true,std:true});});values.addHistogram(responseNumeric);values.addHistogram(throughputNumeric);values.addHistogram(frameTimeDiscrepancyNumeric);values.addHistogram(latencyNumeric);}tr.metrics.MetricRegistry.register(responsivenessMetric,{supportsRangeOfInterest:true});return{responsivenessMetric:responsivenessMetric};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/system_health_metrics.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/system_health_metrics.js

Statements: 64.29% (9 / 14)      Branches: 100% (0 / 0)      Functions: 50% (1 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./cpu_time_metric.js");require("./hazard_metric.js");require("./long_tasks_metric.js");require("./power_metric.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){function systemHealthMetrics(values,model){tr.metrics.sh.responsivenessMetric(values,model);tr.metrics.sh.longTasksMetric(values,model);tr.metrics.sh.hazardMetric(values,model);tr.metrics.sh.powerMetric(values,model);tr.metrics.sh.cpuTimeMetric(values,model);}tr.metrics.MetricRegistry.register(systemHealthMetrics);return{systemHealthMetrics:systemHealthMetrics};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/utils.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/utils.js

Statements: 42.86% (6 / 14)      Branches: 0% (0 / 6)      Functions: 25% (1 / 4)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../model/user_model/user_expectation.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){function perceptualBlend(ir,index,score){return Math.exp(1-score);}function filterExpectationsByRange(irs,opt_range){var filteredExpectations=[];irs.forEach(function(ir){if(!(ir instanceof tr.model.um.UserExpectation))return;if(!opt_range||opt_range.intersectsExplicitRangeInclusive(ir.start,ir.end))filteredExpectations.push(ir);});return filteredExpectations;}return{perceptualBlend:perceptualBlend,filterExpectationsByRange:filterExpectationsByRange};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/webview_startup_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/system_health/webview_startup_metric.js

Statements: 27.59% (8 / 29)      Branches: 0% (0 / 6)      Functions: 50% (1 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../metric_registry.js");require("./utils.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.sh',function(){function webviewStartupMetric(values,model){var startupWallHist=new tr.v.Histogram('webview_startup_wall_time',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter);startupWallHist.description='WebView startup wall time';var startupCPUHist=new tr.v.Histogram('webview_startup_cpu_time',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter);startupCPUHist.description='WebView startup CPU time';var loadWallHist=new tr.v.Histogram('webview_url_load_wall_time',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter);loadWallHist.description='WebView blank URL load wall time';var loadCPUHist=new tr.v.Histogram('webview_url_load_cpu_time',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter);loadCPUHist.description='WebView blank URL load CPU time';for(var slice of model.getDescendantEvents()){if(!(slice instanceof tr.model.ThreadSlice))continue;if(slice.title==='WebViewStartupInterval'){startupWallHist.addSample(slice.duration);startupCPUHist.addSample(slice.cpuDuration);}if(slice.title==='WebViewBlankUrlLoadInterval'){loadWallHist.addSample(slice.duration);loadCPUHist.addSample(slice.cpuDuration);}}values.addHistogram(startupWallHist);values.addHistogram(startupCPUHist);values.addHistogram(loadWallHist);values.addHistogram(loadCPUHist);}tr.metrics.MetricRegistry.register(webviewStartupMetric);return{webviewStartupMetric:webviewStartupMetric};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/v8/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/v8/

Statements: 24.11% (95 / 394)      Branches: 0% (0 / 58)      Functions: 6.06% (4 / 66)      Lines: 100% (4 / 4)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/v8/
File Statements Branches Functions Lines
execution_metric.js 14.53% (17 / 117) 100% (0 / 0) 11.11% (1 / 9) 100% (1 / 1)
gc_metric.js 24.63% (33 / 134) 0% (0 / 14) 3.13% (1 / 32) 100% (1 / 1)
utils.js 27.48% (36 / 131) 0% (0 / 44) 4.35% (1 / 23) 100% (1 / 1)
v8_metrics.js 75% (9 / 12) 100% (0 / 0) 50% (1 / 2) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/v8/execution_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/v8/execution_metric.js

Statements: 14.53% (17 / 117)      Branches: 100% (0 / 0)      Functions: 11.11% (1 / 9)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/range.js");require("../../base/unit.js");require("../metric_registry.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.v8',function(){var CUSTOM_BOUNDARIES=tr.v.HistogramBinBoundaries.createLinear(4,200,100);function computeExecuteMetrics(values,model){var cpuTotalExecution=new tr.v.Histogram('v8_execution_cpu_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuTotalExecution.description='cpu total time spent in script execution';var wallTotalExecution=new tr.v.Histogram('v8_execution_wall_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallTotalExecution.description='wall total time spent in script execution';var cpuSelfExecution=new tr.v.Histogram('v8_execution_cpu_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuSelfExecution.description='cpu self time spent in script execution';var wallSelfExecution=new tr.v.Histogram('v8_execution_wall_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallSelfExecution.description='wall self time spent in script execution';for(var e of model.findTopmostSlicesNamed('V8.Execute')){cpuTotalExecution.addSample(e.cpuDuration);wallTotalExecution.addSample(e.duration);cpuSelfExecution.addSample(e.cpuSelfTime);wallSelfExecution.addSample(e.selfTime);}values.addHistogram(cpuTotalExecution);values.addHistogram(wallTotalExecution);values.addHistogram(cpuSelfExecution);values.addHistogram(wallSelfExecution);}function computeParseLazyMetrics(values,model){var cpuSelfParseLazy=new tr.v.Histogram('v8_parse_lazy_cpu_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuSelfParseLazy.description='cpu self time spent performing lazy parsing';var wallSelfParseLazy=new tr.v.Histogram('v8_parse_lazy_wall_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallSelfParseLazy.description='wall self time spent performing lazy parsing';for(var e of model.findTopmostSlicesNamed('V8.ParseLazyMicroSeconds')){cpuSelfParseLazy.addSample(e.cpuSelfTime);wallSelfParseLazy.addSample(e.selfTime);}for(var e of model.findTopmostSlicesNamed('V8.ParseLazy')){cpuSelfParseLazy.addSample(e.cpuSelfTime);wallSelfParseLazy.addSample(e.selfTime);}values.addHistogram(cpuSelfParseLazy);values.addHistogram(wallSelfParseLazy);}function computeCompileFullCodeMetrics(values,model){var cpuSelfCompileFullCode=new tr.v.Histogram('v8_compile_full_code_cpu_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuSelfCompileFullCode.description='cpu self time spent performing compiling full code';var wallSelfCompileFullCode=new tr.v.Histogram('v8_compile_full_code_wall_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallSelfCompileFullCode.description='wall self time spent performing compiling full code';for(var e of model.findTopmostSlicesNamed('V8.CompileFullCode')){cpuSelfCompileFullCode.addSample(e.cpuSelfTime);wallSelfCompileFullCode.addSample(e.selfTime);}values.addHistogram(cpuSelfCompileFullCode);values.addHistogram(wallSelfCompileFullCode);}function computeCompileIgnitionMetrics(values,model){var cpuSelfCompileIgnition=new tr.v.Histogram('v8_compile_ignition_cpu_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuSelfCompileIgnition.description='cpu self time spent in compile ignition';var wallSelfCompileIgnition=new tr.v.Histogram('v8_compile_ignition_wall_self',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallSelfCompileIgnition.description='wall self time spent in compile ignition';for(var e of model.findTopmostSlicesNamed('V8.CompileIgnition')){cpuSelfCompileIgnition.addSample(e.cpuSelfTime);wallSelfCompileIgnition.addSample(e.selfTime);}values.addHistogram(cpuSelfCompileIgnition);values.addHistogram(wallSelfCompileIgnition);}function computeRecompileMetrics(values,model){var cpuTotalRecompileSynchronous=new tr.v.Histogram('v8_recompile_synchronous_cpu_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuTotalRecompileSynchronous.description='cpu total time spent in synchronous recompilation';var wallTotalRecompileSynchronous=new tr.v.Histogram('v8_recompile_synchronous_wall_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallTotalRecompileSynchronous.description='wall total time spent in synchronous recompilation';var cpuTotalRecompileConcurrent=new tr.v.Histogram('v8_recompile_concurrent_cpu_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuTotalRecompileConcurrent.description='cpu total time spent in concurrent recompilation';var wallTotalRecompileConcurrent=new tr.v.Histogram('v8_recompile_concurrent_wall_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallTotalRecompileConcurrent.description='wall total time spent in concurrent recompilation';var cpuTotalRecompileOverall=new tr.v.Histogram('v8_recompile_overall_cpu_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuTotalRecompileOverall.description='cpu total time spent in synchronous or concurrent recompilation';var wallTotalRecompileOverall=new tr.v.Histogram('v8_recompile_overall_wall_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallTotalRecompileOverall.description='wall total time spent in synchronous or concurrent recompilation';for(var e of model.findTopmostSlicesNamed('V8.RecompileSynchronous')){cpuTotalRecompileSynchronous.addSample(e.cpuDuration);wallTotalRecompileSynchronous.addSample(e.duration);cpuTotalRecompileOverall.addSample(e.cpuDuration);wallTotalRecompileOverall.addSample(e.duration);}values.addHistogram(cpuTotalRecompileSynchronous);values.addHistogram(wallTotalRecompileSynchronous);for(var e of model.findTopmostSlicesNamed('V8.RecompileConcurrent')){cpuTotalRecompileConcurrent.addSample(e.cpuDuration);wallTotalRecompileConcurrent.addSample(e.duration);cpuTotalRecompileOverall.addSample(e.cpuDuration);wallTotalRecompileOverall.addSample(e.duration);}values.addHistogram(cpuTotalRecompileConcurrent);values.addHistogram(wallTotalRecompileConcurrent);values.addHistogram(cpuTotalRecompileOverall);values.addHistogram(wallTotalRecompileOverall);}function computeOptimizeCodeMetrics(values,model){var cpuTotalOptimizeCode=new tr.v.Histogram('v8_optimize_code_cpu_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuTotalOptimizeCode.description='cpu total time spent in code optimization';var wallTotalOptimizeCode=new tr.v.Histogram('v8_optimize_code_wall_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallTotalOptimizeCode.description='wall total time spent in code optimization';for(var e of model.findTopmostSlicesNamed('V8.OptimizeCode')){cpuTotalOptimizeCode.addSample(e.cpuDuration);wallTotalOptimizeCode.addSample(e.duration);}values.addHistogram(cpuTotalOptimizeCode);values.addHistogram(wallTotalOptimizeCode);}function computeDeoptimizeCodeMetrics(values,model){var cpuTotalDeoptimizeCode=new tr.v.Histogram('v8_deoptimize_code_cpu_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);cpuTotalDeoptimizeCode.description='cpu total time spent in code deoptimization';var wallTotalDeoptimizeCode=new tr.v.Histogram('v8_deoptimize_code_wall_total',tr.b.Unit.byName.timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);wallTotalDeoptimizeCode.description='wall total time spent in code deoptimization';for(var e of model.findTopmostSlicesNamed('V8.DeoptimizeCode')){cpuTotalDeoptimizeCode.addSample(e.cpuDuration);wallTotalDeoptimizeCode.addSample(e.duration);}values.addHistogram(cpuTotalDeoptimizeCode);values.addHistogram(wallTotalDeoptimizeCode);}function executionMetric(values,model){computeExecuteMetrics(values,model);computeParseLazyMetrics(values,model);computeCompileIgnitionMetrics(values,model);computeCompileFullCodeMetrics(values,model);computeRecompileMetrics(values,model);computeOptimizeCodeMetrics(values,model);computeDeoptimizeCodeMetrics(values,model);}tr.metrics.MetricRegistry.register(executionMetric);return{executionMetric:executionMetric};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/v8/gc_metric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/v8/gc_metric.js

Statements: 24.63% (33 / 134)      Branches: 0% (0 / 14)      Functions: 3.13% (1 / 32)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/range.js");require("../../base/unit.js");require("../metric_registry.js");require("./utils.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.v8',function(){var TARGET_FPS=60;var MS_PER_SECOND=1000;var WINDOW_SIZE_MS=MS_PER_SECOND/TARGET_FPS;function gcMetric(values,model){addDurationOfTopEvents(values,model);addTotalDurationOfTopEvents(values,model);addDurationOfSubEvents(values,model);addIdleTimesOfTopEvents(values,model);addTotalIdleTimesOfTopEvents(values,model);addPercentageInV8ExecuteOfTopEvents(values,model);addTotalPercentageInV8Execute(values,model);addV8ExecuteMutatorUtilization(values,model);}tr.metrics.MetricRegistry.register(gcMetric);var timeDurationInMs_smallerIsBetter=tr.b.Unit.byName.timeDurationInMs_smallerIsBetter;var percentage_biggerIsBetter=tr.b.Unit.byName.normalizedPercentage_biggerIsBetter;var percentage_smallerIsBetter=tr.b.Unit.byName.normalizedPercentage_smallerIsBetter;var CUSTOM_BOUNDARIES=tr.v.HistogramBinBoundaries.createLinear(0,20,200).addExponentialBins(200,100);function createNumericForTopEventTime(name){var n=new tr.v.Histogram(name,timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);n.customizeSummaryOptions({avg:true,count:true,max:true,min:false,std:true,sum:true,percentile:[0.90]});return n;}function createNumericForSubEventTime(name){var n=new tr.v.Histogram(name,timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);n.customizeSummaryOptions({avg:true,count:false,max:true,min:false,std:false,sum:false,percentile:[0.90]});return n;}function createNumericForIdleTime(name){var n=new tr.v.Histogram(name,timeDurationInMs_smallerIsBetter,CUSTOM_BOUNDARIES);n.customizeSummaryOptions({avg:true,count:false,max:true,min:false,std:false,sum:true,percentile:[]});return n;}function createPercentage(name,numerator,denominator,unit){var hist=new tr.v.Histogram(name,unit);if(denominator===0)hist.addSample(0);else hist.addSample(numerator/denominator);hist.customizeSummaryOptions({avg:true,count:false,max:false,min:false,std:false,sum:false,percentile:[]});return hist;}function isNotForcedTopGarbageCollectionEvent(event){return tr.metrics.v8.utils.isTopGarbageCollectionEvent(event)&&!tr.metrics.v8.utils.isForcedGarbageCollectionEvent(event);}function isNotForcedSubGarbageCollectionEvent(event){return tr.metrics.v8.utils.isSubGarbageCollectionEvent(event)&&!tr.metrics.v8.utils.isForcedGarbageCollectionEvent(event);}function addDurationOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedTopGarbageCollectionEvent,tr.metrics.v8.utils.topGarbageCollectionEventName,function(name,events){var cpuDuration=createNumericForTopEventTime(name);events.forEach(function(event){cpuDuration.addSample(event.cpuDuration);});values.addHistogram(cpuDuration);});}function addTotalDurationOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedTopGarbageCollectionEvent,event=>'v8-gc-total',function(name,events){var cpuDuration=createNumericForTopEventTime(name);events.forEach(function(event){cpuDuration.addSample(event.cpuDuration);});values.addHistogram(cpuDuration);});}function addDurationOfSubEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedSubGarbageCollectionEvent,tr.metrics.v8.utils.subGarbageCollectionEventName,function(name,events){var cpuDuration=createNumericForSubEventTime(name);events.forEach(function(event){cpuDuration.addSample(event.cpuDuration);});values.addHistogram(cpuDuration);});}function addIdleTimesOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedTopGarbageCollectionEvent,tr.metrics.v8.utils.topGarbageCollectionEventName,function(name,events){addIdleTimes(values,model,name,events);});}function addTotalIdleTimesOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedTopGarbageCollectionEvent,event=>'v8-gc-total',function(name,events){addIdleTimes(values,model,name,events);});}function addIdleTimes(values,model,name,events){var cpuDuration=createNumericForIdleTime();var insideIdle=createNumericForIdleTime();var outsideIdle=createNumericForIdleTime(name+'_outside_idle');var idleDeadlineOverrun=createNumericForIdleTime(name+'_idle_deadline_overrun');events.forEach(function(event){var idleTask=tr.metrics.v8.utils.findParent(event,tr.metrics.v8.utils.isIdleTask);var inside=0;var overrun=0;if(idleTask){var allottedTime=idleTask['args']['allotted_time_ms'];if(event.duration>allottedTime){overrun=event.duration-allottedTime;inside=event.cpuDuration*allottedTime/event.duration;}else{inside=event.cpuDuration;}}cpuDuration.addSample(event.cpuDuration);insideIdle.addSample(inside);outsideIdle.addSample(event.cpuDuration-inside);idleDeadlineOverrun.addSample(overrun);});values.addHistogram(idleDeadlineOverrun);values.addHistogram(outsideIdle);var percentage=createPercentage(name+'_percentage_idle',insideIdle.sum,cpuDuration.sum,percentage_biggerIsBetter);values.addHistogram(percentage);}function addPercentageInV8ExecuteOfTopEvents(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedTopGarbageCollectionEvent,tr.metrics.v8.utils.topGarbageCollectionEventName,function(name,events){addPercentageInV8Execute(values,model,name,events);});}function addTotalPercentageInV8Execute(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,isNotForcedTopGarbageCollectionEvent,event=>'v8-gc-total',function(name,events){addPercentageInV8Execute(values,model,name,events);});}function addPercentageInV8Execute(values,model,name,events){var cpuDurationInV8Execute=0;var cpuDurationTotal=0;events.forEach(function(event){var v8Execute=tr.metrics.v8.utils.findParent(event,tr.metrics.v8.utils.isV8ExecuteEvent);if(v8Execute){cpuDurationInV8Execute+=event.cpuDuration;}cpuDurationTotal+=event.cpuDuration;});var percentage=createPercentage(name+'_percentage_in_v8_execute',cpuDurationInV8Execute,cpuDurationTotal,percentage_smallerIsBetter);values.addHistogram(percentage);}function addV8ExecuteMutatorUtilization(values,model){tr.metrics.v8.utils.groupAndProcessEvents(model,tr.metrics.v8.utils.isTopV8ExecuteEvent,event=>'v8-execute',function(name,events){events.sort((a,b)=>a.start-b.start);var time=0;var pauses=[];for(var topEvent of events){for(var e of topEvent.enumerateAllDescendents()){if(isNotForcedTopGarbageCollectionEvent(e)){pauses.push({start:e.start-topEvent.start+time,end:e.end-topEvent.start+time});}}time+=topEvent.duration;}var mutatorUtilization=tr.metrics.v8.utils.mutatorUtilization(0,time,WINDOW_SIZE_MS,pauses);[0.90,0.95,0.99].forEach(function(percent){var hist=new tr.v.Histogram('v8-execute-mutator-utilization_pct_0'+percent*100,percentage_biggerIsBetter);hist.addSample(mutatorUtilization.percentile(1.0-percent));values.addHistogram(hist);});var hist=new tr.v.Histogram('v8-execute-mutator-utilization_min',percentage_biggerIsBetter);hist.addSample(mutatorUtilization.min);values.addHistogram(hist);});}return{gcMetric:gcMetric,WINDOW_SIZE_MS:WINDOW_SIZE_MS};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/v8/utils.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/v8/utils.js

Statements: 27.48% (36 / 131)      Branches: 0% (0 / 44)      Functions: 4.35% (1 / 23)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/piecewise_linear_function.js");require("../../base/range.js");require("../../base/range_utils.js");require("../../base/unit.js");require("../metric_registry.js");require("../../value/histogram.js");'use strict';global.tr.exportTo('tr.metrics.v8.utils',function(){var IDLE_TASK_EVENT='SingleThreadIdleTaskRunner::RunTask';var V8_EXECUTE='V8.Execute';var GC_EVENT_PREFIX='V8.GC';var FULL_GC_EVENT='V8.GCCompactor';var LOW_MEMORY_EVENT='V8.GCLowMemoryNotification';var MAJOR_GC_EVENT='MajorGC';var MINOR_GC_EVENT='MinorGC';var TOP_GC_EVENTS={'V8.GCCompactor':'v8-gc-full-mark-compactor','V8.GCFinalizeMC':'v8-gc-latency-mark-compactor','V8.GCFinalizeMCReduceMemory':'v8-gc-memory-mark-compactor','V8.GCIncrementalMarking':'v8-gc-incremental-step','V8.GCIncrementalMarkingFinalize':'v8-gc-incremental-finalize','V8.GCIncrementalMarkingStart':'v8-gc-incremental-start','V8.GCPhantomHandleProcessingCallback':'v8-gc-phantom-handle-callback','V8.GCScavenger':'v8-gc-scavenger'};var LOW_MEMORY_MARK_COMPACTOR='v8-gc-low-memory-mark-compactor';function findParent(event,predicate){var parent=event.parentSlice;while(parent){if(predicate(parent)){return parent;}parent=parent.parentSlice;}return null;}function isIdleTask(event){return event.title===IDLE_TASK_EVENT;}function isLowMemoryEvent(event){return event.title===LOW_MEMORY_EVENT;}function isV8ExecuteEvent(event){return event.title===V8_EXECUTE;}function isTopV8ExecuteEvent(event){return isV8ExecuteEvent(event)&&findParent(isV8ExecuteEvent)===null;}function isGarbageCollectionEvent(event){return event.title&&event.title.startsWith(GC_EVENT_PREFIX)&&event.title!=LOW_MEMORY_EVENT;}function isTopGarbageCollectionEvent(event){return event.title in TOP_GC_EVENTS;}function isForcedGarbageCollectionEvent(event){return findParent(event,isLowMemoryEvent)!==null;}function isSubGarbageCollectionEvent(event){return isGarbageCollectionEvent(event)&&event.parentSlice&&(isTopGarbageCollectionEvent(event.parentSlice)||event.parentSlice.title===MAJOR_GC_EVENT||event.parentSlice.title===MINOR_GC_EVENT);}function topGarbageCollectionEventName(event){if(event.title===FULL_GC_EVENT){if(findParent(event,isLowMemoryEvent)){return LOW_MEMORY_MARK_COMPACTOR;}}return TOP_GC_EVENTS[event.title];}function subGarbageCollectionEventName(event){var topEvent=findParent(event,isTopGarbageCollectionEvent);var prefix=topEvent?topGarbageCollectionEventName(topEvent):'unknown';var name=event.title.replace('V8.GC_MC_','').replace('V8.GC_SCAVENGER_','').replace('V8.GC_','').replace(/_/g,'-').toLowerCase();return prefix+'-'+name;}function groupAndProcessEvents(model,filterCallback,nameCallback,processCallback){var nameToEvents={};for(var event of model.getDescendantEvents()){if(!filterCallback(event))continue;var name=nameCallback(event);nameToEvents[name]=nameToEvents[name]||[];nameToEvents[name].push(event);}tr.b.iterItems(nameToEvents,function(name,events){processCallback(name,events);});}function unionOfIntervals(intervals){if(intervals.length===0)return[];return tr.b.mergeRanges(intervals.map(x=>({min:x.start,max:x.end})),1e-6,function(ranges){return{start:ranges.reduce((acc,x)=>Math.min(acc,x.min),ranges[0].min),end:ranges.reduce((acc,x)=>Math.max(acc,x.max),ranges[0].max)};});}function WindowEndpoint(start,points){this.points=points;this.lastIndex=-1;this.position=start;this.distanceUntilNextPoint=points[0].position-start;this.cummulativePause=0;this.stackDepth=0;}WindowEndpoint.prototype={advance:function(delta){var points=this.points;if(delta<this.distanceUntilNextPoint){this.position+=delta;this.cummulativePause+=this.stackDepth>0?delta:0;this.distanceUntilNextPoint=points[this.lastIndex+1].position-this.position;}else{this.position+=this.distanceUntilNextPoint;this.cummulativePause+=this.stackDepth>0?this.distanceUntilNextPoint:0;this.distanceUntilNextPoint=0;this.lastIndex++;if(this.lastIndex<points.length){this.stackDepth+=points[this.lastIndex].delta;if(this.lastIndex+1<points.length)this.distanceUntilNextPoint=points[this.lastIndex+1].position-this.position;}}}};function mutatorUtilization(start,end,timeWindow,intervals){var mu=new tr.b.PiecewiseLinearFunction();if(end-start<=timeWindow)return mu;if(intervals.length===0){mu.push(start,1.0,end-timeWindow,1.0);return mu;}intervals=unionOfIntervals(intervals);var points=[];intervals.forEach(function(interval){points.push({position:interval.start,delta:1});points.push({position:interval.end,delta:-1});});points.sort((a,b)=>a.position-b.position);points.push({position:end,delta:0});var left=new WindowEndpoint(start,points);var right=new WindowEndpoint(start,points);while(right.position-left.position<timeWindow)right.advance(timeWindow-(right.position-left.position));while(right.lastIndex<points.length){var distanceUntilNextPoint=Math.min(left.distanceUntilNextPoint,right.distanceUntilNextPoint);var position1=left.position;var value1=right.cummulativePause-left.cummulativePause;left.advance(distanceUntilNextPoint);right.advance(distanceUntilNextPoint);if(distanceUntilNextPoint>0){var position2=left.position;var value2=right.cummulativePause-left.cummulativePause;mu.push(position1,1.0-value1/timeWindow,position2,1.0-value2/timeWindow);}}return mu;}function hasV8Stats(globalMemoryDump){var v8stats=undefined;globalMemoryDump.iterateContainerDumps(function(dump){v8stats=v8stats||dump.getMemoryAllocatorDumpByFullName('v8');});return!!v8stats;}function rangeForMemoryDumps(model){var startOfFirstDumpWithV8=model.globalMemoryDumps.filter(hasV8Stats).reduce((start,dump)=>Math.min(start,dump.start),Infinity);if(startOfFirstDumpWithV8===Infinity)return new tr.b.Range();return tr.b.Range.fromExplicitRange(startOfFirstDumpWithV8,Infinity);}return{findParent:findParent,groupAndProcessEvents:groupAndProcessEvents,isForcedGarbageCollectionEvent:isForcedGarbageCollectionEvent,isGarbageCollectionEvent:isGarbageCollectionEvent,isIdleTask:isIdleTask,isLowMemoryEvent:isLowMemoryEvent,isSubGarbageCollectionEvent:isSubGarbageCollectionEvent,isTopGarbageCollectionEvent:isTopGarbageCollectionEvent,isTopV8ExecuteEvent:isTopV8ExecuteEvent,isV8ExecuteEvent:isV8ExecuteEvent,mutatorUtilization:mutatorUtilization,subGarbageCollectionEventName:subGarbageCollectionEventName,topGarbageCollectionEventName:topGarbageCollectionEventName,rangeForMemoryDumps:rangeForMemoryDumps,unionOfIntervals:unionOfIntervals};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/v8/v8_metrics.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/metrics/v8/v8_metrics.js

Statements: 75% (9 / 12)      Branches: 100% (0 / 0)      Functions: 50% (1 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../metric_registry.js");require("../system_health/memory_metric.js");require("./execution_metric.js");require("./gc_metric.js");'use strict';global.tr.exportTo('tr.metrics.v8',function(){function v8AndMemoryMetrics(values,model){tr.metrics.v8.executionMetric(values,model);tr.metrics.v8.gcMetric(values,model);tr.metrics.sh.memoryMetric(values,model,{rangeOfInterest:tr.metrics.v8.utils.rangeForMemoryDumps(model)});}tr.metrics.MetricRegistry.register(v8AndMemoryMetrics);return{v8AndMemoryMetrics:v8AndMemoryMetrics};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/

Statements: 18.77% (637 / 3393)      Branches: 0.76% (8 / 1059)      Functions: 7.88% (61 / 774)      Lines: 100% (55 / 55)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/
File Statements Branches Functions Lines
alert.js 52.63% (10 / 19) 0% (0 / 2) 16.67% (1 / 6) 100% (1 / 1)
annotation.js 43.75% (14 / 32) 20% (2 / 10) 18.18% (2 / 11) 100% (1 / 1)
async_slice.js 12.12% (8 / 66) 0% (0 / 18) 8.33% (1 / 12) 100% (1 / 1)
async_slice_group.js 14.06% (9 / 64) 0% (0 / 18) 6.25% (1 / 16) 100% (1 / 1)
clock_sync_manager.js 15.04% (17 / 113) 0% (0 / 48) 9.52% (2 / 21) 100% (1 / 1)
comment_box_annotation.js 55% (11 / 20) 100% (0 / 0) 16.67% (1 / 6) 100% (1 / 1)
compound_event_selection_state.js 100% (5 / 5) 100% (0 / 0) 100% (1 / 1) 100% (1 / 1)
constants.js 100% (4 / 4) 100% (0 / 0) 100% (1 / 1) 100% (1 / 1)
container_memory_dump.js 26.67% (8 / 30) 0% (0 / 8) 10% (1 / 10) 100% (1 / 1)
counter.js 14.29% (10 / 70) 0% (0 / 12) 4.17% (1 / 24) 100% (1 / 1)
counter_sample.js 33.33% (12 / 36) 100% (0 / 0) 7.69% (1 / 13) 100% (1 / 1)
counter_series.js 20% (8 / 40) 100% (0 / 0) 6.67% (1 / 15) 100% (1 / 1)
cpu.js 14.15% (15 / 106) 0% (0 / 34) 4.35% (1 / 23) 100% (1 / 1)
cpu_slice.js 37.5% (9 / 24) 0% (0 / 6) 25% (1 / 4) 100% (1 / 1)
device.js 28.57% (10 / 35) 0% (0 / 4) 6.25% (1 / 16) 100% (1 / 1)
event.js 52% (13 / 25) 0% (0 / 2) 14.29% (1 / 7) 100% (1 / 1)
event_container.js 30.77% (8 / 26) 100% (0 / 0) 7.14% (1 / 14) 100% (1 / 1)
event_info.js 60% (6 / 10) 100% (0 / 0) 50% (1 / 2) 100% (1 / 1)
event_registry.js 60.47% (26 / 43) 50% (5 / 10) 33.33% (3 / 9) 100% (1 / 1)
event_set.js 15.91% (21 / 132) 2.08% (1 / 48) 8.82% (3 / 34) 100% (1 / 1)
flow_event.js 36.36% (8 / 22) 0% (0 / 4) 33.33% (1 / 3) 100% (1 / 1)
frame.js 37.14% (13 / 35) 0% (0 / 2) 11.11% (1 / 9) 100% (1 / 1)
global_memory_dump.js 9.67% (26 / 269) 0% (0 / 107) 1.72% (1 / 58) 100% (1 / 1)
heap_dump.js 38.89% (7 / 18) 100% (0 / 0) 25% (1 / 4) 100% (1 / 1)
instant_event.js 52% (13 / 25) 0% (0 / 2) 16.67% (1 / 6) 100% (1 / 1)
ir_coverage.js 22.5% (9 / 40) 0% (0 / 10) 12.5% (1 / 8) 100% (1 / 1)
kernel.js 24.44% (11 / 45) 0% (0 / 8) 6.25% (1 / 16) 100% (1 / 1)
location.js 15.63% (10 / 64) 0% (0 / 14) 10% (1 / 10) 100% (1 / 1)
memory_allocator_dump.js 18.99% (15 / 79) 0% (0 / 25) 6.67% (1 / 15) 100% (1 / 1)
model.js 14.38% (43 / 299) 0% (0 / 73) 1.41% (1 / 71) 100% (1 / 1)
model_indices.js 33.33% (6 / 18) 0% (0 / 8) 20% (1 / 5) 100% (1 / 1)
model_stats.js 18.75% (6 / 32) 0% (0 / 6) 16.67% (1 / 6) 100% (1 / 1)
object_collection.js 12.62% (13 / 103) 0% (0 / 30) 3.13% (1 / 32) 100% (1 / 1)
object_instance.js 11.83% (11 / 93) 0% (0 / 48) 6.25% (1 / 16) 100% (1 / 1)
object_snapshot.js 57.14% (8 / 14) 100% (0 / 0) 14.29% (1 / 7) 100% (1 / 1)
power_sample.js 50% (10 / 20) 100% (0 / 0) 12.5% (1 / 8) 100% (1 / 1)
power_series.js 21.57% (11 / 51) 0% (0 / 6) 9.09% (1 / 11) 100% (1 / 1)
process.js 15% (12 / 80) 0% (0 / 22) 6.25% (1 / 16) 100% (1 / 1)
process_base.js 15.05% (14 / 93) 0% (0 / 16) 4% (1 / 25) 100% (1 / 1)
process_memory_dump.js 16% (16 / 100) 0% (0 / 47) 8.33% (1 / 12) 100% (1 / 1)
rect_annotation.js 45.45% (10 / 22) 100% (0 / 0) 14.29% (1 / 7) 100% (1 / 1)
sample.js 42.11% (8 / 19) 0% (0 / 2) 16.67% (1 / 6) 100% (1 / 1)
scoped_id.js 58.33% (7 / 12) 0% (0 / 2) 33.33% (1 / 3) 100% (1 / 1)
selectable_item.js 38.89% (7 / 18) 0% (0 / 4) 16.67% (1 / 6) 100% (1 / 1)
selection_state.js 84.62% (11 / 13) 100% (0 / 0) 33.33% (1 / 3) 100% (1 / 1)
slice.js 6.31% (7 / 111) 0% (0 / 28) 4.55% (1 / 22) 100% (1 / 1)
slice_group.js 5.86% (17 / 290) 0% (0 / 137) 2.27% (1 / 44) 100% (1 / 1)
stack_frame.js 12.24% (6 / 49) 0% (0 / 22) 7.69% (1 / 13) 100% (1 / 1)
thread.js 12.34% (19 / 154) 0% (0 / 66) 3.03% (1 / 33) 100% (1 / 1)
thread_slice.js 47.06% (8 / 17) 0% (0 / 8) 25% (1 / 4) 100% (1 / 1)
thread_time_slice.js 18.18% (10 / 55) 0% (0 / 34) 16.67% (1 / 6) 100% (1 / 1)
time_to_object_instance_map.js 7.87% (7 / 89) 0% (0 / 46) 8.33% (1 / 12) 100% (1 / 1)
timed_event.js 36.36% (8 / 22) 0% (0 / 4) 20% (1 / 5) 100% (1 / 1)
vm_region.js 15.89% (17 / 107) 0% (0 / 58) 4.55% (1 / 22) 100% (1 / 1)
x_marker_annotation.js 60% (9 / 15) 100% (0 / 0) 20% (1 / 5) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/alert.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/alert.js

Statements: 52.63% (10 / 19)      Branches: 0% (0 / 2)      Functions: 16.67% (1 / 6)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/unit.js");require("./event_info.js");require("./event_set.js");require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){function Alert(info,start,opt_associatedEvents,opt_args){tr.model.TimedEvent.call(this,start);this.info=info;this.args=opt_args||{};this.associatedEvents=new tr.model.EventSet(opt_associatedEvents);this.associatedEvents.forEach(function(event){event.addAssociatedAlert(this);},this);}Alert.prototype={__proto__:tr.model.TimedEvent.prototype,get title(){return this.info.title;},get colorId(){return this.info.colorId;},get userFriendlyName(){return'Alert '+this.title+' at '+tr.b.Unit.byName.timeStampInMs.format(this.start);}};tr.model.EventRegistry.register(Alert,{name:'alert',pluralName:'alerts'});return{Alert:Alert};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/annotation.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/annotation.js

Statements: 43.75% (14 / 32)      Branches: 20% (2 / 10)      Functions: 18.18% (2 / 11)      Lines: 100% (1 / 1)      Ignored: none     

1 23  
"use strict";require("../base/extension_registry.js");require("../base/guid.js");'use strict';global.tr.exportTo('tr.model',function(){function Annotation(){this.guid_=tr.b.GUID.allocateSimple();this.view_=undefined;};Annotation.fromDictIfPossible=function(args){if(args.typeName===undefined)throw new Error('Missing typeName argument');var typeInfo=Annotation.findTypeInfoMatching(function(typeInfo){return typeInfo.metadata.typeName===args.typeName;});if(typeInfo===undefined)return undefined;return typeInfo.constructor.fromDict(args);};Annotation.fromDict=function(){throw new Error('Not implemented');};Annotation.prototype={get guid(){return this.guid_;},onRemove:function(){},toDict:function(){throw new Error('Not implemented');},getOrCreateView:function(viewport){if(!this.view_)this.view_=this.createView_(viewport);return this.view_;},createView_:function(){throw new Error('Not implemented');}};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);tr.b.decorateExtensionRegistry(Annotation,options);Annotation.addEventListener('will-register',function(e){Iif(!e.typeInfo.constructor.hasOwnProperty('fromDict'))throw new Error('Must have fromDict method');Iif(!e.typeInfo.metadata.typeName)throw new Error('Registered Annotations must provide typeName');});return{Annotation:Annotation};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/async_slice.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/async_slice.js

Statements: 12.12% (8 / 66)      Branches: 0% (0 / 18)      Functions: 8.33% (1 / 12)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/unit.js");require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){function AsyncSlice(category,title,colorId,start,args,duration,opt_isTopLevel,opt_cpuStart,opt_cpuDuration,opt_argsStripped){tr.model.TimedEvent.call(this,start);this.category=category||'';this.originalTitle=title;this.title=title;this.colorId=colorId;this.args=args;this.startStackFrame=undefined;this.endStackFrame=undefined;this.didNotFinish=false;this.important=false;this.subSlices=[];this.parentContainer_=undefined;this.id=undefined;this.startThread=undefined;this.endThread=undefined;this.cpuStart=undefined;this.cpuDuration=undefined;this.argsStripped=false;this.startStackFrame=undefined;this.endStackFrame=undefined;this.duration=duration;this.isTopLevel=opt_isTopLevel===true;if(opt_cpuStart!==undefined)this.cpuStart=opt_cpuStart;if(opt_cpuDuration!==undefined)this.cpuDuration=opt_cpuDuration;if(opt_argsStripped!==undefined)this.argsStripped=opt_argsStripped;}AsyncSlice.prototype={__proto__:tr.model.TimedEvent.prototype,get analysisTypeName(){return this.title;},get parentContainer(){return this.parentContainer_;},set parentContainer(parentContainer){this.parentContainer_=parentContainer;for(var i=0;i<this.subSlices.length;i++){var subSlice=this.subSlices[i];if(subSlice.parentContainer===undefined)subSlice.parentContainer=parentContainer;}},get viewSubGroupTitle(){return this.title;},get userFriendlyName(){return'Async slice '+this.title+' at '+tr.b.Unit.byName.timeStampInMs.format(this.start);},get stableId(){var parentAsyncSliceGroup=this.parentContainer.asyncSliceGroup;return parentAsyncSliceGroup.stableId+'.'+parentAsyncSliceGroup.slices.indexOf(this);},findTopmostSlicesRelativeToThisSlice:function*(eventPredicate,opt_this){if(eventPredicate(this)){yield this;return;}for(var s of this.subSlices)yield*s.findTopmostSlicesRelativeToThisSlice(eventPredicate);},findDescendentSlice:function(targetTitle){if(!this.subSlices)return undefined;for(var i=0;i<this.subSlices.length;i++){if(this.subSlices[i].title==targetTitle)return this.subSlices[i];var slice=this.subSlices[i].findDescendentSlice(targetTitle);if(slice)return slice;}return undefined;},enumerateAllDescendents:function*(){for(var slice of this.subSlices)yield slice;for(var slice of this.subSlices)yield*slice.enumerateAllDescendents();},compareTo:function(that){return this.title.localeCompare(that.title);}};tr.model.EventRegistry.register(AsyncSlice,{name:'asyncSlice',pluralName:'asyncSlices'});return{AsyncSlice:AsyncSlice};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/async_slice_group.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/async_slice_group.js

Statements: 14.06% (9 / 64)      Branches: 0% (0 / 18)      Functions: 6.25% (1 / 16)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/guid.js");require("../base/range.js");require("./async_slice.js");require("./event_container.js");'use strict';global.tr.exportTo('tr.model',function(){function AsyncSliceGroup(parentContainer,opt_name){tr.model.EventContainer.call(this);this.parentContainer_=parentContainer;this.slices=[];this.name_=opt_name;this.viewSubGroups_=undefined;}AsyncSliceGroup.prototype={__proto__:tr.model.EventContainer.prototype,get parentContainer(){return this.parentContainer_;},get model(){return this.parentContainer_.parent.model;},get stableId(){return this.parentContainer_.stableId+'.AsyncSliceGroup';},getSettingsKey:function(){if(!this.name_)return undefined;var parentKey=this.parentContainer_.getSettingsKey();if(!parentKey)return undefined;return parentKey+'.'+this.name_;},push:function(slice){slice.parentContainer=this.parentContainer;this.slices.push(slice);return slice;},get length(){return this.slices.length;},shiftTimestampsForward:function(amount){for(var sI=0;sI<this.slices.length;sI++){var slice=this.slices[sI];slice.start=slice.start+amount;var shiftSubSlices=function(subSlices){if(subSlices===undefined||subSlices.length===0)return;for(var sJ=0;sJ<subSlices.length;sJ++){subSlices[sJ].start+=amount;shiftSubSlices(subSlices[sJ].subSlices);}};shiftSubSlices(slice.subSlices);}},updateBounds:function(){this.bounds.reset();for(var i=0;i<this.slices.length;i++){this.bounds.addValue(this.slices[i].start);this.bounds.addValue(this.slices[i].end);}},get viewSubGroups(){if(this.viewSubGroups_===undefined){var prefix='';if(this.name!==undefined)prefix=this.name+'.';else prefix='';var subGroupsByTitle={};for(var i=0;i<this.slices.length;++i){var slice=this.slices[i];var subGroupTitle=slice.viewSubGroupTitle;if(!subGroupsByTitle[subGroupTitle]){subGroupsByTitle[subGroupTitle]=new AsyncSliceGroup(this.parentContainer_,prefix+subGroupTitle);}subGroupsByTitle[subGroupTitle].push(slice);}this.viewSubGroups_=tr.b.dictionaryValues(subGroupsByTitle);this.viewSubGroups_.sort(function(a,b){return a.slices[0].compareTo(b.slices[0]);});}return this.viewSubGroups_;},findTopmostSlicesInThisContainer:function*(eventPredicate,opt_this){for(var slice of this.slices){if(slice.isTopLevel){yield*slice.findTopmostSlicesRelativeToThisSlice(eventPredicate,opt_this);}}},childEvents:function*(){for(var slice of this.slices){yield slice;if(slice.subSlices)yield*slice.subSlices;}},childEventContainers:function*(){}};return{AsyncSliceGroup:AsyncSliceGroup};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/clock_sync_manager.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/clock_sync_manager.js

Statements: 15.04% (17 / 113)      Branches: 0% (0 / 48)      Functions: 9.52% (2 / 21)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/iteration_helpers.js");'use strict';global.tr.exportTo('tr.model',function(){var ClockDomainId={BATTOR:'BATTOR',UNKNOWN_CHROME_LEGACY:'UNKNOWN_CHROME_LEGACY',LINUX_CLOCK_MONOTONIC:'LINUX_CLOCK_MONOTONIC',LINUX_FTRACE_GLOBAL:'LINUX_FTRACE_GLOBAL',MAC_MACH_ABSOLUTE_TIME:'MAC_MACH_ABSOLUTE_TIME',WIN_ROLLOVER_PROTECTED_TIME_GET_TIME:'WIN_ROLLOVER_PROTECTED_TIME_GET_TIME',WIN_QPC:'WIN_QPC',TELEMETRY:'TELEMETRY'};var POSSIBLE_CHROME_CLOCK_DOMAINS=new Set([ClockDomainId.UNKNOWN_CHROME_LEGACY,ClockDomainId.LINUX_CLOCK_MONOTONIC,ClockDomainId.MAC_MACH_ABSOLUTE_TIME,ClockDomainId.WIN_ROLLOVER_PROTECTED_TIME_GET_TIME,ClockDomainId.WIN_QPC]);var BATTOR_FAST_SYNC_THRESHOLD_MS=3;function ClockSyncManager(){this.domainsSeen_=new Set();this.markersBySyncId_=new Map();this.transformerMapByDomainId_={};}ClockSyncManager.prototype={addClockSyncMarker:function(domainId,syncId,startTs,opt_endTs){this.onDomainSeen_(domainId);if(tr.b.dictionaryValues(ClockDomainId).indexOf(domainId)<0){throw new Error('"'+domainId+'" is not in the list of known '+'clock domain IDs.');}if(this.modelDomainId_){throw new Error('Cannot add new clock sync markers after getting '+'a model time transformer.');}var marker=new ClockSyncMarker(domainId,startTs,opt_endTs);if(!this.markersBySyncId_.has(syncId)){this.markersBySyncId_.set(syncId,[marker]);return;}var markers=this.markersBySyncId_.get(syncId);if(markers.length===2){throw new Error('Clock sync with ID "'+syncId+'" is already '+'complete - cannot add a third clock sync marker to it.');}if(markers[0].domainId===domainId)throw new Error('A clock domain cannot sync with itself.');markers.push(marker);this.onSyncCompleted_(markers[0],marker);},get markersBySyncId(){return this.markersBySyncId_;},get domainsSeen(){return this.domainsSeen_;},getModelTimeTransformer:function(domainId){return this.getModelTimeTransformerRaw_(domainId).fn;},getModelTimeTransformerError:function(domainId){return this.getModelTimeTransformerRaw_(domainId).error;},getModelTimeTransformerRaw_:function(domainId){this.onDomainSeen_(domainId);if(!this.modelDomainId_)this.selectModelDomainId_();var transformer=this.getTransformerBetween_(domainId,this.modelDomainId_);if(!transformer){throw new Error('No clock sync markers exist pairing clock domain "'+domainId+'" '+'with model clock domain "'+this.modelDomainId_+'".');}return transformer;},getTransformerBetween_:function(fromDomainId,toDomainId){var visitedDomainIds=new Set();var queue=[{domainId:fromDomainId,transformer:Transformer.IDENTITY}];while(queue.length>0){queue.sort((domain1,domain2)=>domain1.transformer.error-domain2.transformer.error);var current=queue.shift();if(current.domainId===toDomainId)return current.transformer;if(visitedDomainIds.has(current.domainId))continue;visitedDomainIds.add(current.domainId);var outgoingTransformers=this.transformerMapByDomainId_[current.domainId];if(!outgoingTransformers)continue;for(var outgoingDomainId in outgoingTransformers){var toNextDomainTransformer=outgoingTransformers[outgoingDomainId];var toCurrentDomainTransformer=current.transformer;queue.push({domainId:outgoingDomainId,transformer:Transformer.compose(toNextDomainTransformer,toCurrentDomainTransformer)});}}return undefined;},selectModelDomainId_:function(){this.ensureAllDomainsAreConnected_();for(var chromeDomainId of POSSIBLE_CHROME_CLOCK_DOMAINS){if(this.domainsSeen_.has(chromeDomainId)){this.modelDomainId_=chromeDomainId;return;}}var domainsSeenArray=Array.from(this.domainsSeen_);domainsSeenArray.sort();this.modelDomainId_=domainsSeenArray[0];},ensureAllDomainsAreConnected_:function(){var firstDomainId=undefined;for(var domainId of this.domainsSeen_){if(!firstDomainId){firstDomainId=domainId;continue;}if(!this.getTransformerBetween_(firstDomainId,domainId)){throw new Error('Unable to select a master clock domain because no '+'path can be found from "'+firstDomainId+'" to "'+domainId+'".');}}return true;},onDomainSeen_:function(domainId){if(domainId===ClockDomainId.UNKNOWN_CHROME_LEGACY&&!this.domainsSeen_.has(ClockDomainId.UNKNOWN_CHROME_LEGACY)){for(var chromeDomainId of POSSIBLE_CHROME_CLOCK_DOMAINS){if(chromeDomainId===ClockDomainId.UNKNOWN_CHROME_LEGACY)continue;this.collapseDomains_(ClockDomainId.UNKNOWN_CHROME_LEGACY,chromeDomainId);}}this.domainsSeen_.add(domainId);},onSyncCompleted_:function(marker1,marker2){var forwardTransformer=Transformer.fromMarkers(marker1,marker2);var backwardTransformer=Transformer.fromMarkers(marker2,marker1);var existingTransformer=this.getOrCreateTransformerMap_(marker1.domainId)[marker2.domainId];if(!existingTransformer||forwardTransformer.error<existingTransformer.error){this.getOrCreateTransformerMap_(marker1.domainId)[marker2.domainId]=forwardTransformer;this.getOrCreateTransformerMap_(marker2.domainId)[marker1.domainId]=backwardTransformer;}},collapseDomains_:function(domain1Id,domain2Id){this.getOrCreateTransformerMap_(domain1Id)[domain2Id]=this.getOrCreateTransformerMap_(domain2Id)[domain1Id]=Transformer.IDENTITY;},getOrCreateTransformerMap_:function(domainId){if(!this.transformerMapByDomainId_[domainId])this.transformerMapByDomainId_[domainId]={};return this.transformerMapByDomainId_[domainId];}};function ClockSyncMarker(domainId,startTs,opt_endTs){this.domainId=domainId;this.startTs=startTs;this.endTs=opt_endTs===undefined?startTs:opt_endTs;}ClockSyncMarker.prototype={get duration(){return this.endTs-this.startTs;},get ts(){return this.startTs+this.duration/2;}};function Transformer(fn,error){this.fn=fn;this.error=error;}Transformer.IDENTITY=new Transformer(tr.b.identity,0);Transformer.compose=function(aToB,bToC){return new Transformer(ts=>bToC.fn(aToB.fn(ts)),aToB.error+bToC.error);};Transformer.fromMarkers=function(fromMarker,toMarker){var fromTs=fromMarker.ts,toTs=toMarker.ts;if(fromMarker.domainId===ClockDomainId.BATTOR&&toMarker.duration>BATTOR_FAST_SYNC_THRESHOLD_MS){toTs=toMarker.startTs;}else if(toMarker.domainId===ClockDomainId.BATTOR&&fromMarker.duration>BATTOR_FAST_SYNC_THRESHOLD_MS){fromTs=fromMarker.startTs;}var tsShift=toTs-fromTs;return new Transformer(ts=>ts+tsShift,fromMarker.duration+toMarker.duration);};return{ClockDomainId:ClockDomainId,ClockSyncManager:ClockSyncManager};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/comment_box_annotation.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/comment_box_annotation.js

Statements: 55% (11 / 20)      Branches: 100% (0 / 0)      Functions: 16.67% (1 / 6)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./location.js");require("./annotation.js");require("./rect_annotation.js");require("../ui/annotations/comment_box_annotation_view.js");'use strict';global.tr.exportTo('tr.model',function(){function CommentBoxAnnotation(location,text){tr.model.Annotation.apply(this,arguments);this.location=location;this.text=text;}CommentBoxAnnotation.fromDict=function(dict){var args=dict.args;var location=new tr.model.Location(args.location.xWorld,args.location.yComponents);return new tr.model.CommentBoxAnnotation(location,args.text);};CommentBoxAnnotation.prototype={__proto__:tr.model.Annotation.prototype,onRemove:function(){this.view_.removeTextArea();},toDict:function(){return{typeName:'comment_box',args:{text:this.text,location:this.location.toDict()}};},createView_:function(viewport){return new tr.ui.annotations.CommentBoxAnnotationView(viewport,this);}};tr.model.Annotation.register(CommentBoxAnnotation,{typeName:'comment_box'});return{CommentBoxAnnotation:CommentBoxAnnotation};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/compound_event_selection_state.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/compound_event_selection_state.js

Statements: 100% (5 / 5)      Branches: 100% (0 / 0)      Functions: 100% (1 / 1)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){var CompoundEventSelectionState={NOT_SELECTED:0,EVENT_SELECTED:0x1,SOME_ASSOCIATED_EVENTS_SELECTED:0x2,ALL_ASSOCIATED_EVENTS_SELECTED:0x4,EVENT_AND_SOME_ASSOCIATED_SELECTED:0x1|0x2,EVENT_AND_ALL_ASSOCIATED_SELECTED:0x1|0x4};return{CompoundEventSelectionState:CompoundEventSelectionState};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/constants.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/constants.js

Statements: 100% (4 / 4)      Branches: 100% (0 / 0)      Functions: 100% (1 / 1)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){return{BROWSER_PROCESS_PID_REF:-1,OBJECT_DEFAULT_SCOPE:'ptr'};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/container_memory_dump.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/container_memory_dump.js

Statements: 26.67% (8 / 30)      Branches: 0% (0 / 8)      Functions: 10% (1 / 10)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){function ContainerMemoryDump(start){tr.model.TimedEvent.call(this,start);this.levelOfDetail=undefined;this.memoryAllocatorDumps_=undefined;this.memoryAllocatorDumpsByFullName_=undefined;};ContainerMemoryDump.LevelOfDetail={BACKGROUND:0,LIGHT:1,DETAILED:2};ContainerMemoryDump.prototype={__proto__:tr.model.TimedEvent.prototype,shiftTimestampsForward:function(amount){this.start+=amount;},get memoryAllocatorDumps(){return this.memoryAllocatorDumps_;},set memoryAllocatorDumps(memoryAllocatorDumps){this.memoryAllocatorDumps_=memoryAllocatorDumps;this.forceRebuildingMemoryAllocatorDumpByFullNameIndex();},getMemoryAllocatorDumpByFullName:function(fullName){if(this.memoryAllocatorDumps_===undefined)return undefined;if(this.memoryAllocatorDumpsByFullName_===undefined){var index={};function addDumpsToIndex(dumps){dumps.forEach(function(dump){index[dump.fullName]=dump;addDumpsToIndex(dump.children);});};addDumpsToIndex(this.memoryAllocatorDumps_);this.memoryAllocatorDumpsByFullName_=index;}return this.memoryAllocatorDumpsByFullName_[fullName];},forceRebuildingMemoryAllocatorDumpByFullNameIndex:function(){this.memoryAllocatorDumpsByFullName_=undefined;},iterateRootAllocatorDumps:function(fn,opt_this){if(this.memoryAllocatorDumps===undefined)return;this.memoryAllocatorDumps.forEach(fn,opt_this||this);}};return{ContainerMemoryDump:ContainerMemoryDump};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/counter.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/counter.js

Statements: 14.29% (10 / 70)      Branches: 0% (0 / 12)      Functions: 4.17% (1 / 24)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/guid.js");require("../base/range.js");require("./counter_series.js");require("./event_container.js");'use strict';global.tr.exportTo('tr.model',function(){function Counter(parent,id,category,name){tr.model.EventContainer.call(this);this.parent_=parent;this.id_=id;this.category_=category||'';this.name_=name;this.series_=[];this.totals=[];}Counter.prototype={__proto__:tr.model.EventContainer.prototype,get parent(){return this.parent_;},get id(){return this.id_;},get category(){return this.category_;},get name(){return this.name_;},childEvents:function*(){},childEventContainers:function*(){yield*this.series;},set timestamps(arg){throw new Error('Bad counter API. No cookie.');},set seriesNames(arg){throw new Error('Bad counter API. No cookie.');},set seriesColors(arg){throw new Error('Bad counter API. No cookie.');},set samples(arg){throw new Error('Bad counter API. No cookie.');},addSeries:function(series){series.counter=this;series.seriesIndex=this.series_.length;this.series_.push(series);return series;},getSeries:function(idx){return this.series_[idx];},get series(){return this.series_;},get numSeries(){return this.series_.length;},get numSamples(){if(this.series_.length===0)return 0;return this.series_[0].length;},get timestamps(){if(this.series_.length===0)return[];return this.series_[0].timestamps;},getSampleStatistics:function(sampleIndices){sampleIndices.sort();var ret=[];this.series_.forEach(function(series){ret.push(series.getStatistics(sampleIndices));});return ret;},shiftTimestampsForward:function(amount){for(var i=0;i<this.series_.length;++i)this.series_[i].shiftTimestampsForward(amount);},updateBounds:function(){this.totals=[];this.maxTotal=0;this.bounds.reset();if(this.series_.length===0)return;var firstSeries=this.series_[0];var lastSeries=this.series_[this.series_.length-1];this.bounds.addValue(firstSeries.getTimestamp(0));this.bounds.addValue(lastSeries.getTimestamp(lastSeries.length-1));var numSeries=this.numSeries;this.maxTotal=-Infinity;for(var i=0;i<firstSeries.length;++i){var total=0;this.series_.forEach(function(series){total+=series.getSample(i).value;this.totals.push(total);}.bind(this));this.maxTotal=Math.max(total,this.maxTotal);}}};Counter.compare=function(x,y){var tmp=x.parent.compareTo(y);if(tmp!=0)return tmp;var tmp=x.name.localeCompare(y.name);if(tmp==0)return x.tid-y.tid;return tmp;};return{Counter:Counter};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/counter_sample.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/counter_sample.js

Statements: 33.33% (12 / 36)      Branches: 100% (0 / 0)      Functions: 7.69% (1 / 13)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/iteration_helpers.js");require("../base/sorted_array_utils.js");require("../base/unit.js");require("./event.js");require("./event_registry.js");'use strict';global.tr.exportTo('tr.model',function(){function CounterSample(series,timestamp,value){tr.model.Event.call(this);this.series_=series;this.timestamp_=timestamp;this.value_=value;}CounterSample.groupByTimestamp=function(samples){var samplesByTimestamp=tr.b.group(samples,function(sample){return sample.timestamp;});var timestamps=tr.b.dictionaryKeys(samplesByTimestamp);timestamps.sort();var groups=[];for(var i=0;i<timestamps.length;i++){var ts=timestamps[i];var group=samplesByTimestamp[ts];group.sort(function(x,y){return x.series.seriesIndex-y.series.seriesIndex;});groups.push(group);}return groups;};CounterSample.prototype={__proto__:tr.model.Event.prototype,get series(){return this.series_;},get timestamp(){return this.timestamp_;},get value(){return this.value_;},set timestamp(timestamp){this.timestamp_=timestamp;},addBoundsToRange:function(range){range.addValue(this.timestamp);},getSampleIndex:function(){return tr.b.findLowIndexInSortedArray(this.series.timestamps,function(x){return x;},this.timestamp_);},get userFriendlyName(){return'Counter sample from '+this.series_.title+' at '+tr.b.Unit.byName.timeStampInMs.format(this.timestamp);}};tr.model.EventRegistry.register(CounterSample,{name:'counterSample',pluralName:'counterSamples'});return{CounterSample:CounterSample};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/counter_series.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/counter_series.js

Statements: 20% (8 / 40)      Branches: 100% (0 / 0)      Functions: 6.67% (1 / 15)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./counter_sample.js");require("./event_container.js");'use strict';global.tr.exportTo('tr.model',function(){var CounterSample=tr.model.CounterSample;function CounterSeries(name,color){tr.model.EventContainer.call(this);this.name_=name;this.color_=color;this.timestamps_=[];this.samples_=[];this.counter=undefined;this.seriesIndex=undefined;}CounterSeries.prototype={__proto__:tr.model.EventContainer.prototype,get length(){return this.timestamps_.length;},get name(){return this.name_;},get color(){return this.color_;},get samples(){return this.samples_;},get timestamps(){return this.timestamps_;},getSample:function(idx){return this.samples_[idx];},getTimestamp:function(idx){return this.timestamps_[idx];},addCounterSample:function(ts,val){var sample=new CounterSample(this,ts,val);this.addSample(sample);return sample;},addSample:function(sample){this.timestamps_.push(sample.timestamp);this.samples_.push(sample);},getStatistics:function(sampleIndices){var sum=0;var min=Number.MAX_VALUE;var max=-Number.MAX_VALUE;for(var i=0;i<sampleIndices.length;++i){var sample=this.getSample(sampleIndices[i]).value;sum+=sample;min=Math.min(sample,min);max=Math.max(sample,max);}return{min:min,max:max,avg:sum/sampleIndices.length,start:this.getSample(sampleIndices[0]).value,end:this.getSample(sampleIndices.length-1).value};},shiftTimestampsForward:function(amount){for(var i=0;i<this.timestamps_.length;++i){this.timestamps_[i]+=amount;this.samples_[i].timestamp=this.timestamps_[i];}},childEvents:function*(){yield*this.samples_;},childEventContainers:function*(){}};return{CounterSeries:CounterSeries};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/cpu.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/cpu.js

Statements: 14.15% (15 / 106)      Branches: 0% (0 / 34)      Functions: 4.35% (1 / 23)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/range.js");require("./counter.js");require("./cpu_slice.js");require("./process_base.js");require("./thread_time_slice.js");'use strict';global.tr.exportTo('tr.model',function(){var ColorScheme=tr.b.ColorScheme;var Counter=tr.model.Counter;var CpuSlice=tr.model.CpuSlice;function Cpu(kernel,number){if(kernel===undefined||number===undefined)throw new Error('Missing arguments');this.kernel=kernel;this.cpuNumber=number;this.slices=[];this.counters={};this.bounds_=new tr.b.Range();this.samples_=undefined;this.lastActiveTimestamp_=undefined;this.lastActiveThread_=undefined;this.lastActiveName_=undefined;this.lastActiveArgs_=undefined;}Cpu.prototype={__proto__:tr.model.EventContainer.prototype,get samples(){return this.samples_;},get userFriendlyName(){return'CPU '+this.cpuNumber;},findTopmostSlicesInThisContainer:function*(eventPredicate,opt_this){for(var s of this.slices){yield*s.findTopmostSlicesRelativeToThisSlice(eventPredicate,opt_this);}},childEvents:function*(){yield*this.slices;if(this.samples_)yield*this.samples_;},childEventContainers:function*(){yield*tr.b.dictionaryValues(this.counters);},getOrCreateCounter:function(cat,name){var id=cat+'.'+name;if(!this.counters[id])this.counters[id]=new Counter(this,id,cat,name);return this.counters[id];},getCounter:function(cat,name){var id=cat+'.'+name;if(!this.counters[id])return undefined;return this.counters[id];},shiftTimestampsForward:function(amount){for(var sI=0;sI<this.slices.length;sI++)this.slices[sI].start=this.slices[sI].start+amount;for(var id in this.counters)this.counters[id].shiftTimestampsForward(amount);},updateBounds:function(){this.bounds_.reset();if(this.slices.length){this.bounds_.addValue(this.slices[0].start);this.bounds_.addValue(this.slices[this.slices.length-1].end);}for(var id in this.counters){this.counters[id].updateBounds();this.bounds_.addRange(this.counters[id].bounds);}if(this.samples_&&this.samples_.length){this.bounds_.addValue(this.samples_[0].start);this.bounds_.addValue(this.samples_[this.samples_.length-1].end);}},createSubSlices:function(){this.samples_=this.kernel.model.samples.filter(function(sample){return sample.cpu==this;},this);},addCategoriesToDict:function(categoriesDict){for(var i=0;i<this.slices.length;i++)categoriesDict[this.slices[i].category]=true;for(var id in this.counters)categoriesDict[this.counters[id].category]=true;for(var i=0;i<this.samples_.length;i++)categoriesDict[this.samples_[i].category]=true;},indexOf:function(cpuSlice){var i=tr.b.findLowIndexInSortedArray(this.slices,function(slice){return slice.start;},cpuSlice.start);if(this.slices[i]!==cpuSlice)return undefined;return i;},closeActiveThread:function(endTimestamp,args){if(this.lastActiveThread_==undefined||this.lastActiveThread_==0)return;if(endTimestamp<this.lastActiveTimestamp_){throw new Error('The end timestamp of a thread running on CPU '+this.cpuNumber+' is before its start timestamp.');}for(var key in args){this.lastActiveArgs_[key]=args[key];}var duration=endTimestamp-this.lastActiveTimestamp_;var slice=new tr.model.CpuSlice('',this.lastActiveName_,ColorScheme.getColorIdForGeneralPurposeString(this.lastActiveName_),this.lastActiveTimestamp_,this.lastActiveArgs_,duration);slice.cpu=this;this.slices.push(slice);this.lastActiveTimestamp_=undefined;this.lastActiveThread_=undefined;this.lastActiveName_=undefined;this.lastActiveArgs_=undefined;},switchActiveThread:function(timestamp,oldThreadArgs,newThreadId,newThreadName,newThreadArgs){this.closeActiveThread(timestamp,oldThreadArgs);this.lastActiveTimestamp_=timestamp;this.lastActiveThread_=newThreadId;this.lastActiveName_=newThreadName;this.lastActiveArgs_=newThreadArgs;},getFreqStatsForRange:function(range){var stats={};function addStatsForFreq(freqSample,index){var freqEnd=index<freqSample.series_.length-1?freqSample.series_.samples_[index+1].timestamp:range.max;var freqRange=tr.b.Range.fromExplicitRange(freqSample.timestamp,freqEnd);var intersection=freqRange.findIntersection(range);if(!(freqSample.value in stats))stats[freqSample.value]=0;stats[freqSample.value]+=intersection.duration;}var freqCounter=this.getCounter('','Clock Frequency');if(freqCounter!==undefined){var freqSeries=freqCounter.getSeries(0);if(!freqSeries)return;tr.b.iterateOverIntersectingIntervals(freqSeries.samples_,function(x){return x.timestamp;},function(x,index){return index<freqSeries.length-1?freqSeries.samples_[index+1].timestamp:range.max;},range.min,range.max,addStatsForFreq);}return stats;}};Cpu.compare=function(x,y){return x.cpuNumber-y.cpuNumber;};return{Cpu:Cpu};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/cpu_slice.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/cpu_slice.js

Statements: 37.5% (9 / 24)      Branches: 0% (0 / 6)      Functions: 25% (1 / 4)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/range.js");require("./thread_time_slice.js");'use strict';global.tr.exportTo('tr.model',function(){var Slice=tr.model.Slice;function CpuSlice(cat,title,colorId,start,args,opt_duration){Slice.apply(this,arguments);this.threadThatWasRunning=undefined;this.cpu=undefined;}CpuSlice.prototype={__proto__:Slice.prototype,get analysisTypeName(){return'tr.ui.analysis.CpuSlice';},getAssociatedTimeslice:function(){if(!this.threadThatWasRunning)return undefined;var timeSlices=this.threadThatWasRunning.timeSlices;for(var i=0;i<timeSlices.length;i++){var timeSlice=timeSlices[i];if(timeSlice.start!==this.start)continue;if(timeSlice.duration!==this.duration)continue;return timeSlice;}return undefined;}};tr.model.EventRegistry.register(CpuSlice,{name:'cpuSlice',pluralName:'cpuSlices'});return{CpuSlice:CpuSlice};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/device.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/device.js

Statements: 28.57% (10 / 35)      Branches: 0% (0 / 4)      Functions: 6.25% (1 / 16)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/guid.js");require("../base/range.js");require("./event_container.js");require("./power_series.js");'use strict';global.tr.exportTo('tr.model',function(){function Device(model){if(!model)throw new Error('Must provide a model.');tr.model.EventContainer.call(this);this.powerSeries_=undefined;this.vSyncTimestamps_=[];};Device.compare=function(x,y){return x.guid-y.guid;};Device.prototype={__proto__:tr.model.EventContainer.prototype,compareTo:function(that){return Device.compare(this,that);},get userFriendlyName(){return'Device';},get userFriendlyDetails(){return'Device';},get stableId(){return'Device';},getSettingsKey:function(){return'device';},get powerSeries(){return this.powerSeries_;},set powerSeries(powerSeries){this.powerSeries_=powerSeries;},get vSyncTimestamps(){return this.vSyncTimestamps_;},set vSyncTimestamps(value){this.vSyncTimestamps_=value;},updateBounds:function(){this.bounds.reset();for(var child of this.childEventContainers()){child.updateBounds();this.bounds.addRange(child.bounds);}},shiftTimestampsForward:function(amount){for(var child of this.childEventContainers()){child.shiftTimestampsForward(amount);}for(var i=0;i<this.vSyncTimestamps_.length;i++)this.vSyncTimestamps_[i]+=amount;},addCategoriesToDict:function(categoriesDict){},childEventContainers:function*(){if(this.powerSeries_)yield this.powerSeries_;}};return{Device:Device};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/event.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/event.js

Statements: 52% (13 / 25)      Branches: 0% (0 / 2)      Functions: 14.29% (1 / 7)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/guid.js");require("../base/range.js");require("./event_set.js");require("./selectable_item.js");require("./selection_state.js");'use strict';global.tr.exportTo('tr.model',function(){var SelectableItem=tr.model.SelectableItem;var SelectionState=tr.model.SelectionState;var IMMUTABLE_EMPTY_SET=tr.model.EventSet.IMMUTABLE_EMPTY_SET;function Event(){SelectableItem.call(this,this);this.guid_=tr.b.GUID.allocateSimple();this.selectionState=SelectionState.NONE;this.info=undefined;}Event.prototype={__proto__:SelectableItem.prototype,get guid(){return this.guid_;},get stableId(){return undefined;},get range(){var range=new tr.b.Range();this.addBoundsToRange(range);return range;},associatedAlerts:IMMUTABLE_EMPTY_SET,addAssociatedAlert:function(alert){if(this.associatedAlerts===IMMUTABLE_EMPTY_SET)this.associatedAlerts=new tr.model.EventSet();this.associatedAlerts.push(alert);},addBoundsToRange:function(range){}};return{Event:Event};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/event_container.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/event_container.js

Statements: 30.77% (8 / 26)      Branches: 100% (0 / 0)      Functions: 7.14% (1 / 14)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");require("../base/guid.js");require("../base/range.js");'use strict';global.tr.exportTo('tr.model',function(){function EventContainer(){this.guid_=tr.b.GUID.allocateSimple();this.important=true;this.bounds_=new tr.b.Range();}EventContainer.prototype={get guid(){return this.guid_;},get stableId(){throw new Error('Not implemented');},get bounds(){return this.bounds_;},updateBounds:function(){throw new Error('Not implemented');},shiftTimestampsForward:function(amount){throw new Error('Not implemented');},childEvents:function*(){},getDescendantEvents:function*(){yield*this.childEvents();for(var container of this.childEventContainers())yield*container.getDescendantEvents();},childEventContainers:function*(){},getDescendantEventContainers:function*(){yield this;for(var container of this.childEventContainers())yield*container.getDescendantEventContainers();},findTopmostSlicesInThisContainer:function*(eventPredicate,opt_this){},findTopmostSlices:function*(eventPredicate){for(var ec of this.getDescendantEventContainers())yield*ec.findTopmostSlicesInThisContainer(eventPredicate);},findTopmostSlicesNamed:function*(name){yield*this.findTopmostSlices(e=>e.title===name);}};return{EventContainer:EventContainer};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/event_info.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/event_info.js

Statements: 60% (6 / 10)      Branches: 100% (0 / 0)      Functions: 50% (1 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/color_scheme.js");'use strict';global.tr.exportTo('tr.model',function(){var ColorScheme=tr.b.ColorScheme;function EventInfo(title,description,docLinks){this.title=title;this.description=description;this.docLinks=docLinks;this.colorId=ColorScheme.getColorIdForGeneralPurposeString(title);}return{EventInfo:EventInfo};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/event_registry.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/event_registry.js

Statements: 60.47% (26 / 43)      Branches: 50% (5 / 10)      Functions: 33.33% (3 / 9)      Lines: 100% (1 / 1)      Ignored: none     

1 216  
"use strict";require("../base/extension_registry.js");'use strict';global.tr.exportTo('tr.model',function(){function EventRegistry(){}var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);tr.b.decorateExtensionRegistry(EventRegistry,options);EventRegistry.addEventListener('will-register',function(e){var metadata=e.typeInfo.metadata;Iif(metadata.name===undefined)throw new Error('Registered events must provide name metadata');Iif(metadata.pluralName===undefined)throw new Error('Registered events must provide pluralName metadata');if(metadata.subTypes===undefined){metadata.subTypes={};var options=new tr.b.ExtensionRegistryOptions(tr.b.TYPE_BASED_REGISTRY_MODE);options.mandatoryBaseClass=e.typeInfo.constructor;options.defaultConstructor=e.typeInfo.constructor;tr.b.decorateExtensionRegistry(metadata.subTypes,options);}else{Iif(!metadata.subTypes.register)throw new Error('metadata.subTypes must be an extension registry.');}e.typeInfo.constructor.subTypes=metadata.subTypes;});var eventsByTypeName=undefined;EventRegistry.getEventTypeInfoByTypeName=function(typeName){if(eventsByTypeName===undefined){eventsByTypeName={};EventRegistry.getAllRegisteredTypeInfos().forEach(function(typeInfo){eventsByTypeName[typeInfo.metadata.name]=typeInfo;});}return eventsByTypeName[typeName];};EventRegistry.addEventListener('registry-changed',function(){eventsByTypeName=undefined;});function convertCamelCaseToTitleCase(name){var result=name.replace(/[A-Z]/g,' $&');result=result.charAt(0).toUpperCase()+result.slice(1);return result;}EventRegistry.getUserFriendlySingularName=function(typeName){var typeInfo=EventRegistry.getEventTypeInfoByTypeName(typeName);var str=typeInfo.metadata.name;return convertCamelCaseToTitleCase(str);};EventRegistry.getUserFriendlyPluralName=function(typeName){var typeInfo=EventRegistry.getEventTypeInfoByTypeName(typeName);var str=typeInfo.metadata.pluralName;return convertCamelCaseToTitleCase(str);};return{EventRegistry:EventRegistry};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/event_set.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/event_set.js

Statements: 15.91% (21 / 132)      Branches: 2.08% (1 / 48)      Functions: 8.82% (3 / 34)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/event.js");require("../base/guid.js");require("../base/iteration_helpers.js");require("../base/range.js");require("./event_registry.js");'use strict';global.tr.exportTo('tr.model',function(){var EventRegistry=tr.model.EventRegistry;var RequestSelectionChangeEvent=tr.b.Event.bind(undefined,'requestSelectionChange',true,false);function EventSet(opt_events){this.bounds_=new tr.b.Range();this.events_=new Set();Iif(opt_events){if(opt_events instanceof Array){for(var event of opt_events)this.push(event);}else if(opt_events instanceof EventSet){this.addEventSet(opt_events);}else{this.push(opt_events);}}}EventSet.prototype={__proto__:Object.prototype,get bounds(){return this.bounds_;},get duration(){if(this.bounds_.isEmpty)return 0;return this.bounds_.max-this.bounds_.min;},get length(){return this.events_.size;},get guid(){return this.guid_;},*[Symbol.iterator](){for(var event of this.events_)yield event;},clear:function(){this.bounds_=new tr.b.Range();this.events_.clear();},push:function(event){if(event.guid==undefined)throw new Error('Event must have a GUID');if(!this.events_.has(event)){this.events_.add(event);if(event.addBoundsToRange)if(this.bounds_!==undefined)event.addBoundsToRange(this.bounds_);}return event;},contains:function(event){if(this.events_.has(event))return event;else return undefined;},addEventSet:function(eventSet){for(var event of eventSet)this.push(event);},intersectionIsEmpty:function(otherEventSet){return!this.some(event=>otherEventSet.contains(event));},equals:function(that){if(this.length!==that.length)return false;return this.every(event=>that.contains(event));},sortEvents:function(compare){var ary=this.toArray();ary.sort(compare);this.clear();for(var event of ary)this.push(event);},getEventsOrganizedByBaseType:function(opt_pruneEmpty){var allTypeInfos=EventRegistry.getAllRegisteredTypeInfos();var events=this.getEventsOrganizedByCallback(function(event){var maxEventIndex=-1;var maxEventTypeInfo=undefined;allTypeInfos.forEach(function(eventTypeInfo,eventIndex){if(!(event instanceof eventTypeInfo.constructor))return;if(eventIndex>maxEventIndex){maxEventIndex=eventIndex;maxEventTypeInfo=eventTypeInfo;}});if(maxEventIndex==-1){console.log(event);throw new Error('Unrecognized event type');}return maxEventTypeInfo.metadata.name;});if(!opt_pruneEmpty){allTypeInfos.forEach(function(eventTypeInfo){if(events[eventTypeInfo.metadata.name]===undefined)events[eventTypeInfo.metadata.name]=new EventSet();});}return events;},getEventsOrganizedByTitle:function(){return this.getEventsOrganizedByCallback(function(event){if(event.title===undefined)throw new Error('An event didn\'t have a title!');return event.title;});},getEventsOrganizedByCallback:function(cb,opt_this){var groupedEvents=tr.b.group(this,cb,opt_this||this);return tr.b.mapItems(groupedEvents,(_,events)=>new EventSet(events));},enumEventsOfType:function(type,func){for(var event of this)if(event instanceof type)func(event);},get userFriendlyName(){if(this.length===0){throw new Error('Empty event set');}var eventsByBaseType=this.getEventsOrganizedByBaseType(true);var eventTypeName=tr.b.dictionaryKeys(eventsByBaseType)[0];if(this.length===1){var tmp=EventRegistry.getUserFriendlySingularName(eventTypeName);return tr.b.getOnlyElement(this.events_).userFriendlyName;}var numEventTypes=tr.b.dictionaryLength(eventsByBaseType);if(numEventTypes!==1){return this.length+' events of various types';}var tmp=EventRegistry.getUserFriendlyPluralName(eventTypeName);return this.length+' '+tmp;},filter:function(fn,opt_this){var res=new EventSet();for(var event of this)if(fn.call(opt_this,event))res.push(event);return res;},toArray:function(){var ary=[];for(var event of this)ary.push(event);return ary;},forEach:function(fn,opt_this){for(var event of this)fn.call(opt_this,event);},map:function(fn,opt_this){var res=[];for(var event of this)res.push(fn.call(opt_this,event));return res;},every:function(fn,opt_this){for(var event of this)if(!fn.call(opt_this,event))return false;return true;},some:function(fn,opt_this){for(var event of this)if(fn.call(opt_this,event))return true;return false;},asDict:function(){var stableIds=[];for(var event of this)stableIds.push(event.stableId);return{'events':stableIds};},asSet:function(){return this.events_;}};EventSet.IMMUTABLE_EMPTY_SET=function(){var s=new EventSet();s.push=function(){throw new Error('Cannot push to an immutable event set');};s.addEventSet=function(){throw new Error('Cannot add to an immutable event set');};Object.freeze(s);return s;}();return{EventSet:EventSet,RequestSelectionChangeEvent:RequestSelectionChangeEvent};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/flow_event.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/flow_event.js

Statements: 36.36% (8 / 22)      Branches: 0% (0 / 4)      Functions: 33.33% (1 / 3)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/unit.js");require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){function FlowEvent(category,id,title,colorId,start,args,opt_duration){tr.model.TimedEvent.call(this,start);this.category=category||'';this.title=title;this.colorId=colorId;this.start=start;this.args=args;this.id=id;this.startSlice=undefined;this.endSlice=undefined;this.startStackFrame=undefined;this.endStackFrame=undefined;if(opt_duration!==undefined)this.duration=opt_duration;}FlowEvent.prototype={__proto__:tr.model.TimedEvent.prototype,get userFriendlyName(){return'Flow event named '+this.title+' at '+tr.b.Unit.byName.timeStampInMs.format(this.timestamp);}};tr.model.EventRegistry.register(FlowEvent,{name:'flowEvent',pluralName:'flowEvents'});return{FlowEvent:FlowEvent};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/frame.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/frame.js

Statements: 37.14% (13 / 35)      Branches: 0% (0 / 2)      Functions: 11.11% (1 / 9)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/color_scheme.js");require("../base/statistics.js");require("./event.js");require("./event_set.js");'use strict';global.tr.exportTo('tr.model',function(){var ColorScheme=tr.b.ColorScheme;var Statistics=tr.b.Statistics;var FRAME_PERF_CLASS={GOOD:'good',BAD:'bad',TERRIBLE:'terrible',NEUTRAL:'generic_work'};function Frame(associatedEvents,threadTimeRanges,opt_args){tr.model.Event.call(this);this.threadTimeRanges=threadTimeRanges;this.associatedEvents=new tr.model.EventSet(associatedEvents);this.args=opt_args||{};this.title='Frame';this.start=Statistics.min(threadTimeRanges,function(x){return x.start;});this.end=Statistics.max(threadTimeRanges,function(x){return x.end;});this.totalDuration=Statistics.sum(threadTimeRanges,function(x){return x.end-x.start;});this.perfClass=FRAME_PERF_CLASS.NEUTRAL;};Frame.prototype={__proto__:tr.model.Event.prototype,set perfClass(perfClass){this.colorId=ColorScheme.getColorIdForReservedName(perfClass);this.perfClass_=perfClass;},get perfClass(){return this.perfClass_;},shiftTimestampsForward:function(amount){this.start+=amount;this.end+=amount;for(var i=0;i<this.threadTimeRanges.length;i++){this.threadTimeRanges[i].start+=amount;this.threadTimeRanges[i].end+=amount;}},addBoundsToRange:function(range){range.addValue(this.start);range.addValue(this.end);}};tr.model.EventRegistry.register(Frame,{name:'frame',pluralName:'frames'});return{Frame:Frame,FRAME_PERF_CLASS:FRAME_PERF_CLASS};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/global_memory_dump.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/global_memory_dump.js

Statements: 9.67% (26 / 269)      Branches: 0% (0 / 107)      Functions: 1.72% (1 / 58)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/iteration_helpers.js");require("../base/unit.js");require("./container_memory_dump.js");require("./event_registry.js");require("./memory_allocator_dump.js");require("../value/numeric.js");'use strict';global.tr.exportTo('tr.model',function(){function GlobalMemoryDump(model,start){tr.model.ContainerMemoryDump.call(this,start);this.model=model;this.processMemoryDumps={};}var SIZE_NUMERIC_NAME=tr.model.MemoryAllocatorDump.SIZE_NUMERIC_NAME;var EFFECTIVE_SIZE_NUMERIC_NAME=tr.model.MemoryAllocatorDump.EFFECTIVE_SIZE_NUMERIC_NAME;var MemoryAllocatorDumpInfoType=tr.model.MemoryAllocatorDumpInfoType;var PROVIDED_SIZE_LESS_THAN_AGGREGATED_CHILDREN=MemoryAllocatorDumpInfoType.PROVIDED_SIZE_LESS_THAN_AGGREGATED_CHILDREN;var PROVIDED_SIZE_LESS_THAN_LARGEST_OWNER=MemoryAllocatorDumpInfoType.PROVIDED_SIZE_LESS_THAN_LARGEST_OWNER;function inPlaceFilter(array,predicate,opt_this){opt_this=opt_this||this;var nextPosition=0;for(var i=0;i<array.length;i++){if(!predicate.call(opt_this,array[i],i))continue;if(nextPosition<i)array[nextPosition]=array[i];nextPosition++;}if(nextPosition<array.length)array.length=nextPosition;}function getSize(dump){var numeric=dump.numerics[SIZE_NUMERIC_NAME];if(numeric===undefined)return 0;return numeric.value;}function hasSize(dump){return dump.numerics[SIZE_NUMERIC_NAME]!==undefined;}function optional(value,defaultValue){if(value===undefined)return defaultValue;return value;}GlobalMemoryDump.prototype={__proto__:tr.model.ContainerMemoryDump.prototype,get userFriendlyName(){return'Global memory dump at '+tr.b.Unit.byName.timeStampInMs.format(this.start);},get containerName(){return'global space';},finalizeGraph:function(){this.removeWeakDumps();this.setUpTracingOverheadOwnership();this.aggregateNumerics();this.calculateSizes();this.calculateEffectiveSizes();this.discountTracingOverheadFromVmRegions();this.forceRebuildingMemoryAllocatorDumpByFullNameIndices();},removeWeakDumps:function(){this.traverseAllocatorDumpsInDepthFirstPreOrder(function(dump){if(dump.weak)return;if(dump.owns!==undefined&&dump.owns.target.weak||dump.parent!==undefined&&dump.parent.weak){dump.weak=true;}});function removeWeakDumpsFromListRecursively(dumps){inPlaceFilter(dumps,function(dump){if(dump.weak){return false;}removeWeakDumpsFromListRecursively(dump.children);inPlaceFilter(dump.ownedBy,function(ownershipLink){return!ownershipLink.source.weak;});return true;});}this.iterateContainerDumps(function(containerDump){var memoryAllocatorDumps=containerDump.memoryAllocatorDumps;if(memoryAllocatorDumps!==undefined)removeWeakDumpsFromListRecursively(memoryAllocatorDumps);});},calculateSizes:function(){this.traverseAllocatorDumpsInDepthFirstPostOrder(this.calculateMemoryAllocatorDumpSize_.bind(this));},calculateMemoryAllocatorDumpSize_:function(dump){var shouldDefineSize=false;function getDependencySize(dependencyDump){var numeric=dependencyDump.numerics[SIZE_NUMERIC_NAME];if(numeric===undefined)return 0;shouldDefineSize=true;return numeric.value;}var sizeNumeric=dump.numerics[SIZE_NUMERIC_NAME];var size=0;var checkDependencySizeIsConsistent=function(){};if(sizeNumeric!==undefined){size=sizeNumeric.value;shouldDefineSize=true;if(sizeNumeric.unit!==tr.b.Unit.byName.sizeInBytes_smallerIsBetter){this.model.importWarning({type:'memory_dump_parse_error',message:'Invalid unit of \'size\' numeric of memory allocator '+'dump '+dump.quantifiedName+': '+sizeNumeric.unit.unitName+'.'});}checkDependencySizeIsConsistent=function(dependencySize,dependencyInfoType,dependencyName){if(size>=dependencySize)return;this.model.importWarning({type:'memory_dump_parse_error',message:'Size provided by memory allocator dump \''+dump.fullName+'\''+tr.b.Unit.byName.sizeInBytes.format(size)+') is less than '+dependencyName+' ('+tr.b.Unit.byName.sizeInBytes.format(dependencySize)+').'});dump.infos.push({type:dependencyInfoType,providedSize:size,dependencySize:dependencySize});}.bind(this);}var aggregatedChildrenSize=0;var allOverlaps={};dump.children.forEach(function(childDump){function aggregateDescendantDump(descendantDump){var ownedDumpLink=descendantDump.owns;if(ownedDumpLink!==undefined&&ownedDumpLink.target.isDescendantOf(dump)){var ownedChildDump=ownedDumpLink.target;while(ownedChildDump.parent!==dump)ownedChildDump=ownedChildDump.parent;if(childDump!==ownedChildDump){var ownedBySiblingSize=getDependencySize(descendantDump);if(ownedBySiblingSize>0){var previousTotalOwnedBySiblingSize=ownedChildDump.ownedBySiblingSizes.get(childDump)||0;var updatedTotalOwnedBySiblingSize=previousTotalOwnedBySiblingSize+ownedBySiblingSize;ownedChildDump.ownedBySiblingSizes.set(childDump,updatedTotalOwnedBySiblingSize);}}return;}if(descendantDump.children.length===0){aggregatedChildrenSize+=getDependencySize(descendantDump);return;}descendantDump.children.forEach(aggregateDescendantDump);}aggregateDescendantDump(childDump);});checkDependencySizeIsConsistent(aggregatedChildrenSize,PROVIDED_SIZE_LESS_THAN_AGGREGATED_CHILDREN,'the aggregated size of its children');var largestOwnerSize=0;dump.ownedBy.forEach(function(ownershipLink){var owner=ownershipLink.source;var ownerSize=getDependencySize(owner);largestOwnerSize=Math.max(largestOwnerSize,ownerSize);});checkDependencySizeIsConsistent(largestOwnerSize,PROVIDED_SIZE_LESS_THAN_LARGEST_OWNER,'the size of its largest owner');if(!shouldDefineSize){delete dump.numerics[SIZE_NUMERIC_NAME];return;}size=Math.max(size,aggregatedChildrenSize,largestOwnerSize);dump.numerics[SIZE_NUMERIC_NAME]=new tr.v.ScalarNumeric(tr.b.Unit.byName.sizeInBytes_smallerIsBetter,size);if(aggregatedChildrenSize<size&&dump.children!==undefined&&dump.children.length>0){var virtualChild=new tr.model.MemoryAllocatorDump(dump.containerMemoryDump,dump.fullName+'/<unspecified>');virtualChild.parent=dump;dump.children.unshift(virtualChild);virtualChild.numerics[SIZE_NUMERIC_NAME]=new tr.v.ScalarNumeric(tr.b.Unit.byName.sizeInBytes_smallerIsBetter,size-aggregatedChildrenSize);}},calculateEffectiveSizes:function(){this.traverseAllocatorDumpsInDepthFirstPostOrder(this.calculateDumpSubSizes_.bind(this));this.traverseAllocatorDumpsInDepthFirstPostOrder(this.calculateDumpOwnershipCoefficient_.bind(this));this.traverseAllocatorDumpsInDepthFirstPreOrder(this.calculateDumpCumulativeOwnershipCoefficient_.bind(this));this.traverseAllocatorDumpsInDepthFirstPostOrder(this.calculateDumpEffectiveSize_.bind(this));},calculateDumpSubSizes_:function(dump){if(!hasSize(dump))return;if(dump.children===undefined||dump.children.length===0){var size=getSize(dump);dump.notOwningSubSize_=size;dump.notOwnedSubSize_=size;return;}var notOwningSubSize=0;dump.children.forEach(function(childDump){if(childDump.owns!==undefined)return;notOwningSubSize+=optional(childDump.notOwningSubSize_,0);});dump.notOwningSubSize_=notOwningSubSize;var notOwnedSubSize=0;dump.children.forEach(function(childDump){if(childDump.ownedBy.length===0){notOwnedSubSize+=optional(childDump.notOwnedSubSize_,0);return;}var largestChildOwnerSize=0;childDump.ownedBy.forEach(function(ownershipLink){largestChildOwnerSize=Math.max(largestChildOwnerSize,getSize(ownershipLink.source));});notOwnedSubSize+=getSize(childDump)-largestChildOwnerSize;});dump.notOwnedSubSize_=notOwnedSubSize;},calculateDumpOwnershipCoefficient_:function(dump){if(!hasSize(dump))return;if(dump.ownedBy.length===0)return;var owners=dump.ownedBy.map(function(ownershipLink){return{dump:ownershipLink.source,importance:optional(ownershipLink.importance,0),notOwningSubSize:optional(ownershipLink.source.notOwningSubSize_,0)};});owners.sort(function(a,b){if(a.importance===b.importance)return a.notOwningSubSize-b.notOwningSubSize;return b.importance-a.importance;});var currentImportanceStartPos=0;var alreadyAttributedSubSize=0;while(currentImportanceStartPos<owners.length){var currentImportance=owners[currentImportanceStartPos].importance;var nextImportanceStartPos=currentImportanceStartPos+1;while(nextImportanceStartPos<owners.length&&owners[nextImportanceStartPos].importance===currentImportance){nextImportanceStartPos++;}var attributedNotOwningSubSize=0;for(var pos=currentImportanceStartPos;pos<nextImportanceStartPos;pos++){var owner=owners[pos];var notOwningSubSize=owner.notOwningSubSize;if(notOwningSubSize>alreadyAttributedSubSize){attributedNotOwningSubSize+=(notOwningSubSize-alreadyAttributedSubSize)/(nextImportanceStartPos-pos);alreadyAttributedSubSize=notOwningSubSize;}var owningCoefficient=0;if(notOwningSubSize!==0)owningCoefficient=attributedNotOwningSubSize/notOwningSubSize;owner.dump.owningCoefficient_=owningCoefficient;}currentImportanceStartPos=nextImportanceStartPos;}var notOwnedSubSize=optional(dump.notOwnedSubSize_,0);var remainderSubSize=notOwnedSubSize-alreadyAttributedSubSize;var ownedCoefficient=0;if(notOwnedSubSize!==0)ownedCoefficient=remainderSubSize/notOwnedSubSize;dump.ownedCoefficient_=ownedCoefficient;},calculateDumpCumulativeOwnershipCoefficient_:function(dump){if(!hasSize(dump))return;var cumulativeOwnedCoefficient=optional(dump.ownedCoefficient_,1);var parent=dump.parent;if(dump.parent!==undefined)cumulativeOwnedCoefficient*=dump.parent.cumulativeOwnedCoefficient_;dump.cumulativeOwnedCoefficient_=cumulativeOwnedCoefficient;var cumulativeOwningCoefficient;if(dump.owns!==undefined){cumulativeOwningCoefficient=dump.owningCoefficient_*dump.owns.target.cumulativeOwningCoefficient_;}else if(dump.parent!==undefined){cumulativeOwningCoefficient=dump.parent.cumulativeOwningCoefficient_;}else{cumulativeOwningCoefficient=1;}dump.cumulativeOwningCoefficient_=cumulativeOwningCoefficient;},calculateDumpEffectiveSize_:function(dump){if(!hasSize(dump)){delete dump.numerics[EFFECTIVE_SIZE_NUMERIC_NAME];return;}var effectiveSize;if(dump.children===undefined||dump.children.length===0){effectiveSize=getSize(dump)*dump.cumulativeOwningCoefficient_*dump.cumulativeOwnedCoefficient_;}else{effectiveSize=0;dump.children.forEach(function(childDump){if(!hasSize(childDump))return;effectiveSize+=childDump.numerics[EFFECTIVE_SIZE_NUMERIC_NAME].value;});}dump.numerics[EFFECTIVE_SIZE_NUMERIC_NAME]=new tr.v.ScalarNumeric(tr.b.Unit.byName.sizeInBytes_smallerIsBetter,effectiveSize);},aggregateNumerics:function(){this.iterateRootAllocatorDumps(function(dump){dump.aggregateNumericsRecursively(this.model);});this.iterateRootAllocatorDumps(this.propagateNumericsAndDiagnosticsRecursively);tr.b.iterItems(this.processMemoryDumps,function(pid,processMemoryDump){processMemoryDump.iterateRootAllocatorDumps(function(dump){dump.aggregateNumericsRecursively(this.model);},this);},this);},propagateNumericsAndDiagnosticsRecursively:function(globalAllocatorDump){['numerics','diagnostics'].forEach(function(field){tr.b.iterItems(globalAllocatorDump[field],function(name,value){globalAllocatorDump.ownedBy.forEach(function(ownershipLink){var processAllocatorDump=ownershipLink.source;if(processAllocatorDump[field][name]!==undefined){return;}processAllocatorDump[field][name]=value;});});});globalAllocatorDump.children.forEach(this.propagateNumericsAndDiagnosticsRecursively,this);},setUpTracingOverheadOwnership:function(){tr.b.iterItems(this.processMemoryDumps,function(pid,dump){dump.setUpTracingOverheadOwnership(this.model);},this);},discountTracingOverheadFromVmRegions:function(){tr.b.iterItems(this.processMemoryDumps,function(pid,dump){dump.discountTracingOverheadFromVmRegions(this.model);},this);},forceRebuildingMemoryAllocatorDumpByFullNameIndices:function(){this.iterateContainerDumps(function(containerDump){containerDump.forceRebuildingMemoryAllocatorDumpByFullNameIndex();});},iterateContainerDumps:function(fn){fn.call(this,this);tr.b.iterItems(this.processMemoryDumps,function(pid,processDump){fn.call(this,processDump);},this);},iterateAllRootAllocatorDumps:function(fn){this.iterateContainerDumps(function(containerDump){containerDump.iterateRootAllocatorDumps(fn,this);});},traverseAllocatorDumpsInDepthFirstPostOrder:function(fn){var visitedDumps=new WeakSet();var openDumps=new WeakSet();function visit(dump){if(visitedDumps.has(dump))return;if(openDumps.has(dump))throw new Error(dump.userFriendlyName+' contains a cycle');openDumps.add(dump);dump.ownedBy.forEach(function(ownershipLink){visit.call(this,ownershipLink.source);},this);dump.children.forEach(visit,this);fn.call(this,dump);visitedDumps.add(dump);openDumps.delete(dump);}this.iterateAllRootAllocatorDumps(visit);},traverseAllocatorDumpsInDepthFirstPreOrder:function(fn){var visitedDumps=new WeakSet();function visit(dump){if(visitedDumps.has(dump))return;if(dump.owns!==undefined&&!visitedDumps.has(dump.owns.target))return;if(dump.parent!==undefined&&!visitedDumps.has(dump.parent))return;fn.call(this,dump);visitedDumps.add(dump);dump.ownedBy.forEach(function(ownershipLink){visit.call(this,ownershipLink.source);},this);dump.children.forEach(visit,this);}this.iterateAllRootAllocatorDumps(visit);}};tr.model.EventRegistry.register(GlobalMemoryDump,{name:'globalMemoryDump',pluralName:'globalMemoryDumps'});return{GlobalMemoryDump:GlobalMemoryDump};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/heap_dump.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/heap_dump.js

Statements: 38.89% (7 / 18)      Branches: 100% (0 / 0)      Functions: 25% (1 / 4)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){function HeapEntry(heapDump,leafStackFrame,objectTypeName,size,count){this.heapDump=heapDump;this.leafStackFrame=leafStackFrame;this.objectTypeName=objectTypeName;this.size=size;this.count=count;}function HeapDump(processMemoryDump,allocatorName){this.processMemoryDump=processMemoryDump;this.allocatorName=allocatorName;this.entries=[];}HeapDump.prototype={addEntry:function(leafStackFrame,objectTypeName,size,count){var entry=new HeapEntry(this,leafStackFrame,objectTypeName,size,count);this.entries.push(entry);return entry;}};return{HeapEntry:HeapEntry,HeapDump:HeapDump};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/instant_event.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/instant_event.js

Statements: 52% (13 / 25)      Branches: 0% (0 / 2)      Functions: 16.67% (1 / 6)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/unit.js");require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){var InstantEventType={GLOBAL:1,PROCESS:2};function InstantEvent(category,title,colorId,start,args){tr.model.TimedEvent.call(this,start);this.category=category||'';this.title=title;this.colorId=colorId;this.args=args;this.type=undefined;}InstantEvent.prototype={__proto__:tr.model.TimedEvent.prototype};function GlobalInstantEvent(category,title,colorId,start,args){InstantEvent.apply(this,arguments);this.type=InstantEventType.GLOBAL;}GlobalInstantEvent.prototype={__proto__:InstantEvent.prototype,get userFriendlyName(){return'Global instant event '+this.title+' @ '+tr.b.Unit.byName.timeStampInMs.format(start);}};function ProcessInstantEvent(category,title,colorId,start,args){InstantEvent.apply(this,arguments);this.type=InstantEventType.PROCESS;}ProcessInstantEvent.prototype={__proto__:InstantEvent.prototype,get userFriendlyName(){return'Process-level instant event '+this.title+' @ '+tr.b.Unit.byName.timeStampInMs.format(start);}};tr.model.EventRegistry.register(InstantEvent,{name:'instantEvent',pluralName:'instantEvents'});return{GlobalInstantEvent:GlobalInstantEvent,ProcessInstantEvent:ProcessInstantEvent,InstantEventType:InstantEventType,InstantEvent:InstantEvent};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/ir_coverage.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/ir_coverage.js

Statements: 22.5% (9 / 40)      Branches: 0% (0 / 10)      Functions: 12.5% (1 / 8)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/iteration_helpers.js");require("./event_set.js");'use strict';global.tr.exportTo('tr.model',function(){function getAssociatedEvents(irs){var allAssociatedEvents=new tr.model.EventSet();irs.forEach(function(ir){ir.associatedEvents.forEach(function(event){if(event instanceof tr.model.FlowEvent)return;allAssociatedEvents.push(event);});});return allAssociatedEvents;}function getUnassociatedEvents(model,associatedEvents){var unassociatedEvents=new tr.model.EventSet();for(var proc of model.getAllProcesses())for(var thread of tr.b.dictionaryValues(proc.threads))for(var event of thread.sliceGroup.getDescendantEvents())if(!associatedEvents.contains(event))unassociatedEvents.push(event);return unassociatedEvents;}function getTotalCpuDuration(events){var cpuMs=0;events.forEach(function(event){if(event.cpuSelfTime)cpuMs+=event.cpuSelfTime;});return cpuMs;}function getIRCoverageFromModel(model){var associatedEvents=getAssociatedEvents(model.userModel.expectations);if(!associatedEvents.length)return undefined;var unassociatedEvents=getUnassociatedEvents(model,associatedEvents);var associatedCpuMs=getTotalCpuDuration(associatedEvents);var unassociatedCpuMs=getTotalCpuDuration(unassociatedEvents);var totalEventCount=associatedEvents.length+unassociatedEvents.length;var totalCpuMs=associatedCpuMs+unassociatedCpuMs;var coveredEventsCpuTimeRatio=undefined;if(totalCpuMs!==0)coveredEventsCpuTimeRatio=associatedCpuMs/totalCpuMs;return{associatedEventsCount:associatedEvents.length,unassociatedEventsCount:unassociatedEvents.length,associatedEventsCpuTimeMs:associatedCpuMs,unassociatedEventsCpuTimeMs:unassociatedCpuMs,coveredEventsCountRatio:associatedEvents.length/totalEventCount,coveredEventsCpuTimeRatio:coveredEventsCpuTimeRatio};}return{getIRCoverageFromModel:getIRCoverageFromModel,getAssociatedEvents:getAssociatedEvents,getUnassociatedEvents:getUnassociatedEvents};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/kernel.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/kernel.js

Statements: 24.44% (11 / 45)      Branches: 0% (0 / 8)      Functions: 6.25% (1 / 16)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/iteration_helpers.js");require("./cpu.js");require("./process_base.js");'use strict';global.tr.exportTo('tr.model',function(){var Cpu=tr.model.Cpu;var ProcessBase=tr.model.ProcessBase;function Kernel(model){ProcessBase.call(this,model);this.cpus={};this.softwareMeasuredCpuCount_=undefined;};Kernel.compare=function(x,y){return 0;};Kernel.prototype={__proto__:ProcessBase.prototype,compareTo:function(that){return Kernel.compare(this,that);},get userFriendlyName(){return'Kernel';},get userFriendlyDetails(){return'Kernel';},get stableId(){return'Kernel';},getOrCreateCpu:function(cpuNumber){if(!this.cpus[cpuNumber])this.cpus[cpuNumber]=new Cpu(this,cpuNumber);return this.cpus[cpuNumber];},get softwareMeasuredCpuCount(){return this.softwareMeasuredCpuCount_;},set softwareMeasuredCpuCount(softwareMeasuredCpuCount){if(this.softwareMeasuredCpuCount_!==undefined&&this.softwareMeasuredCpuCount_!==softwareMeasuredCpuCount){throw new Error('Cannot change the softwareMeasuredCpuCount once it is set');}this.softwareMeasuredCpuCount_=softwareMeasuredCpuCount;},get bestGuessAtCpuCount(){var realCpuCount=tr.b.dictionaryLength(this.cpus);if(realCpuCount!==0)return realCpuCount;return this.softwareMeasuredCpuCount;},updateBounds:function(){ProcessBase.prototype.updateBounds.call(this);for(var cpuNumber in this.cpus){var cpu=this.cpus[cpuNumber];cpu.updateBounds();this.bounds.addRange(cpu.bounds);}},createSubSlices:function(){ProcessBase.prototype.createSubSlices.call(this);for(var cpuNumber in this.cpus){var cpu=this.cpus[cpuNumber];cpu.createSubSlices();}},addCategoriesToDict:function(categoriesDict){ProcessBase.prototype.addCategoriesToDict.call(this,categoriesDict);for(var cpuNumber in this.cpus)this.cpus[cpuNumber].addCategoriesToDict(categoriesDict);},getSettingsKey:function(){return'kernel';},childEventContainers:function*(){yield*ProcessBase.prototype.childEventContainers.call(this);yield*tr.b.dictionaryValues(this.cpus);}};return{Kernel:Kernel};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/location.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/location.js

Statements: 15.63% (10 / 64)      Branches: 0% (0 / 14)      Functions: 10% (1 / 10)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){function YComponent(stableId,yPercentOffset){this.stableId=stableId;this.yPercentOffset=yPercentOffset;}YComponent.prototype={toDict:function(){return{stableId:this.stableId,yPercentOffset:this.yPercentOffset};}};function Location(xWorld,yComponents){this.xWorld_=xWorld;this.yComponents_=yComponents;};Location.fromViewCoordinates=function(viewport,viewX,viewY){var dt=viewport.currentDisplayTransform;var xWorld=dt.xViewToWorld(viewX);var yComponents=[];var elem=document.elementFromPoint(viewX+viewport.modelTrackContainer.canvas.offsetLeft,viewY+viewport.modelTrackContainer.canvas.offsetTop);while(elem instanceof tr.ui.tracks.Track){if(elem.eventContainer){var boundRect=elem.getBoundingClientRect();var yPercentOffset=(viewY-boundRect.top)/boundRect.height;yComponents.push(new YComponent(elem.eventContainer.stableId,yPercentOffset));}elem=elem.parentElement;}if(yComponents.length==0)return;return new Location(xWorld,yComponents);};Location.fromStableIdAndTimestamp=function(viewport,stableId,ts){var xWorld=ts;var yComponents=[];var containerToTrack=viewport.containerToTrackMap;var elem=containerToTrack.getTrackByStableId(stableId);if(!elem)return;var firstY=elem.getBoundingClientRect().top;while(elem instanceof tr.ui.tracks.Track){if(elem.eventContainer){var boundRect=elem.getBoundingClientRect();var yPercentOffset=(firstY-boundRect.top)/boundRect.height;yComponents.push(new YComponent(elem.eventContainer.stableId,yPercentOffset));}elem=elem.parentElement;}if(yComponents.length==0)return;return new Location(xWorld,yComponents);};Location.prototype={get xWorld(){return this.xWorld_;},getContainingTrack:function(viewport){var containerToTrack=viewport.containerToTrackMap;for(var i in this.yComponents_){var yComponent=this.yComponents_[i];var track=containerToTrack.getTrackByStableId(yComponent.stableId);if(track!==undefined)return track;}},toViewCoordinates:function(viewport){var dt=viewport.currentDisplayTransform;var containerToTrack=viewport.containerToTrackMap;var viewX=dt.xWorldToView(this.xWorld_);var viewY=-1;for(var index in this.yComponents_){var yComponent=this.yComponents_[index];var track=containerToTrack.getTrackByStableId(yComponent.stableId);if(track!==undefined){var boundRect=track.getBoundingClientRect();viewY=yComponent.yPercentOffset*boundRect.height+boundRect.top;break;}}return{viewX:viewX,viewY:viewY};},toDict:function(){return{xWorld:this.xWorld_,yComponents:this.yComponents_};}};return{Location:Location};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/memory_allocator_dump.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/memory_allocator_dump.js

Statements: 18.99% (15 / 79)      Branches: 0% (0 / 25)      Functions: 6.67% (1 / 15)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/iteration_helpers.js");require("../base/unit.js");require("../value/numeric.js");'use strict';global.tr.exportTo('tr.model',function(){function MemoryAllocatorDump(containerMemoryDump,fullName,opt_guid){this.fullName=fullName;this.parent=undefined;this.children=[];this.numerics={};this.diagnostics={};this.containerMemoryDump=containerMemoryDump;this.owns=undefined;this.ownedBy=[];this.ownedBySiblingSizes=new Map();this.retains=[];this.retainedBy=[];this.weak=false;this.infos=[];this.guid=opt_guid;}MemoryAllocatorDump.SIZE_NUMERIC_NAME='size';MemoryAllocatorDump.EFFECTIVE_SIZE_NUMERIC_NAME='effective_size';MemoryAllocatorDump.RESIDENT_SIZE_NUMERIC_NAME='resident_size';MemoryAllocatorDump.DISPLAYED_SIZE_NUMERIC_NAME=MemoryAllocatorDump.EFFECTIVE_SIZE_NUMERIC_NAME;MemoryAllocatorDump.prototype={get name(){return this.fullName.substring(this.fullName.lastIndexOf('/')+1);},get quantifiedName(){return'\''+this.fullName+'\' in '+this.containerMemoryDump.containerName;},getDescendantDumpByFullName:function(fullName){return this.containerMemoryDump.getMemoryAllocatorDumpByFullName(this.fullName+'/'+fullName);},isDescendantOf:function(otherDump){var dump=this;while(dump!==undefined){if(dump===otherDump)return true;dump=dump.parent;}return false;},addNumeric:function(name,numeric){if(!(numeric instanceof tr.v.ScalarNumeric))throw new Error('Numeric value must be an instance of ScalarNumeric.');if(name in this.numerics)throw new Error('Duplicate numeric name: '+name+'.');this.numerics[name]=numeric;},addDiagnostic:function(name,text){if(typeof text!=='string')throw new Error('Diagnostic text must be a string.');if(name in this.diagnostics)throw new Error('Duplicate diagnostic name: '+name+'.');this.diagnostics[name]=text;},aggregateNumericsRecursively:function(opt_model){var numericNames=new Set();this.children.forEach(function(child){child.aggregateNumericsRecursively(opt_model);tr.b.iterItems(child.numerics,numericNames.add,numericNames);},this);numericNames.forEach(function(numericName){if(numericName===MemoryAllocatorDump.SIZE_NUMERIC_NAME||numericName===MemoryAllocatorDump.EFFECTIVE_SIZE_NUMERIC_NAME||this.numerics[numericName]!==undefined){return;}this.numerics[numericName]=MemoryAllocatorDump.aggregateNumerics(this.children.map(function(child){return child.numerics[numericName];}),opt_model);},this);}};MemoryAllocatorDump.aggregateNumerics=function(numerics,opt_model){var shouldLogWarning=!!opt_model;var aggregatedUnit=undefined;var aggregatedValue=0;numerics.forEach(function(numeric){if(numeric===undefined)return;var unit=numeric.unit;if(aggregatedUnit===undefined){aggregatedUnit=unit;}else if(aggregatedUnit!==unit){if(shouldLogWarning){opt_model.importWarning({type:'numeric_parse_error',message:'Multiple units provided for numeric: \''+aggregatedUnit.unitName+'\' and \''+unit.unitName+'\'.'});shouldLogWarning=false;}aggregatedUnit=tr.b.Unit.byName.unitlessNumber_smallerIsBetter;}aggregatedValue+=numeric.value;},this);if(aggregatedUnit===undefined)return undefined;return new tr.v.ScalarNumeric(aggregatedUnit,aggregatedValue);};function MemoryAllocatorDumpLink(source,target,opt_importance){this.source=source;this.target=target;this.importance=opt_importance;this.size=undefined;}var MemoryAllocatorDumpInfoType={PROVIDED_SIZE_LESS_THAN_AGGREGATED_CHILDREN:0,PROVIDED_SIZE_LESS_THAN_LARGEST_OWNER:1};return{MemoryAllocatorDump:MemoryAllocatorDump,MemoryAllocatorDumpLink:MemoryAllocatorDumpLink,MemoryAllocatorDumpInfoType:MemoryAllocatorDumpInfoType};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/model.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/model.js

Statements: 14.38% (43 / 299)      Branches: 0% (0 / 73)      Functions: 1.41% (1 / 71)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");require("../base/event.js");require("../base/interval_tree.js");require("../base/quad.js");require("../base/range.js");require("../base/task.js");require("../base/time_display_modes.js");require("../base/unit.js");require("../core/auditor.js");require("../core/filter.js");require("./alert.js");require("./clock_sync_manager.js");require("./constants.js");require("./device.js");require("./flow_event.js");require("./frame.js");require("./global_memory_dump.js");require("./instant_event.js");require("./kernel.js");require("./model_indices.js");require("./model_stats.js");require("./object_snapshot.js");require("./process.js");require("./process_memory_dump.js");require("./sample.js");require("./stack_frame.js");require("./user_model/user_expectation.js");require("./user_model/user_model.js");'use strict';global.tr.exportTo('tr',function(){var Process=tr.model.Process;var Device=tr.model.Device;var Kernel=tr.model.Kernel;var GlobalMemoryDump=tr.model.GlobalMemoryDump;var GlobalInstantEvent=tr.model.GlobalInstantEvent;var FlowEvent=tr.model.FlowEvent;var Alert=tr.model.Alert;var Sample=tr.model.Sample;function Model(){tr.model.EventContainer.call(this);tr.b.EventTarget.decorate(this);this.timestampShiftToZeroAmount_=0;this.faviconHue='blue';this.device=new Device(this);this.kernel=new Kernel(this);this.processes={};this.metadata=[];this.categories=[];this.instantEvents=[];this.flowEvents=[];this.clockSyncManager=new tr.model.ClockSyncManager();this.intrinsicTimeUnit_=undefined;this.stackFrames={};this.samples=[];this.alerts=[];this.userModel=new tr.model.um.UserModel(this);this.flowIntervalTree=new tr.b.IntervalTree(f=>f.start,f=>f.end);this.globalMemoryDumps=[];this.userFriendlyCategoryDrivers_=[];this.annotationsByGuid_={};this.modelIndices=undefined;this.stats=new tr.model.ModelStats();this.importWarnings_=[];this.reportedImportWarnings_={};this.isTimeHighResolution_=true;this.patchupsToApply_=[];this.doesHelperGUIDSupportThisModel_={};this.helpersByConstructorGUID_={};this.eventsByStableId_=undefined;}Model.prototype={__proto__:tr.model.EventContainer.prototype,getEventByStableId:function(stableId){if(this.eventsByStableId_===undefined){this.eventsByStableId_={};for(var event of this.getDescendantEvents()){this.eventsByStableId_[event.stableId]=event;}}return this.eventsByStableId_[stableId];},getOrCreateHelper:function(constructor){if(!constructor.guid)throw new Error('Helper constructors must have GUIDs');if(this.helpersByConstructorGUID_[constructor.guid]===undefined){if(this.doesHelperGUIDSupportThisModel_[constructor.guid]===undefined){this.doesHelperGUIDSupportThisModel_[constructor.guid]=constructor.supportsModel(this);}if(!this.doesHelperGUIDSupportThisModel_[constructor.guid])return undefined;this.helpersByConstructorGUID_[constructor.guid]=new constructor(this);}return this.helpersByConstructorGUID_[constructor.guid];},childEvents:function*(){yield*this.globalMemoryDumps;yield*this.instantEvents;yield*this.flowEvents;yield*this.alerts;yield*this.samples;},childEventContainers:function*(){yield this.userModel;yield this.device;yield this.kernel;yield*tr.b.dictionaryValues(this.processes);},iterateAllPersistableObjects:function(callback){this.kernel.iterateAllPersistableObjects(callback);for(var pid in this.processes)this.processes[pid].iterateAllPersistableObjects(callback);},updateBounds:function(){this.bounds.reset();var bounds=this.bounds;for(var ec of this.childEventContainers()){ec.updateBounds();bounds.addRange(ec.bounds);}for(var event of this.childEvents())event.addBoundsToRange(bounds);},shiftWorldToZero:function(){var shiftAmount=-this.bounds.min;this.timestampShiftToZeroAmount_=shiftAmount;for(var ec of this.childEventContainers())ec.shiftTimestampsForward(shiftAmount);for(var event of this.childEvents())event.start+=shiftAmount;this.updateBounds();},convertTimestampToModelTime:function(sourceClockDomainName,ts){if(sourceClockDomainName!=='traceEventClock')throw new Error('Only traceEventClock is supported.');return tr.b.Unit.timestampFromUs(ts)+this.timestampShiftToZeroAmount_;},get numProcesses(){var n=0;for(var p in this.processes)n++;return n;},getProcess:function(pid){return this.processes[pid];},getOrCreateProcess:function(pid){if(!this.processes[pid])this.processes[pid]=new Process(this,pid);return this.processes[pid];},addStackFrame:function(stackFrame){if(this.stackFrames[stackFrame.id])throw new Error('Stack frame already exists');this.stackFrames[stackFrame.id]=stackFrame;return stackFrame;},updateCategories_:function(){var categoriesDict={};this.userModel.addCategoriesToDict(categoriesDict);this.device.addCategoriesToDict(categoriesDict);this.kernel.addCategoriesToDict(categoriesDict);for(var pid in this.processes)this.processes[pid].addCategoriesToDict(categoriesDict);this.categories=[];for(var category in categoriesDict)if(category!='')this.categories.push(category);},getAllThreads:function(){var threads=[];for(var tid in this.kernel.threads){threads.push(process.threads[tid]);}for(var pid in this.processes){var process=this.processes[pid];for(var tid in process.threads){threads.push(process.threads[tid]);}}return threads;},getAllProcesses:function(opt_predicate){var processes=[];for(var pid in this.processes){var process=this.processes[pid];if(opt_predicate===undefined||opt_predicate(process))processes.push(process);}return processes;},getAllCounters:function(){var counters=[];counters.push.apply(counters,tr.b.dictionaryValues(this.device.counters));counters.push.apply(counters,tr.b.dictionaryValues(this.kernel.counters));for(var pid in this.processes){var process=this.processes[pid];for(var tid in process.counters){counters.push(process.counters[tid]);}}return counters;},getAnnotationByGUID:function(guid){return this.annotationsByGuid_[guid];},addAnnotation:function(annotation){if(!annotation.guid)throw new Error('Annotation with undefined guid given');this.annotationsByGuid_[annotation.guid]=annotation;tr.b.dispatchSimpleEvent(this,'annotationChange');},removeAnnotation:function(annotation){this.annotationsByGuid_[annotation.guid].onRemove();delete this.annotationsByGuid_[annotation.guid];tr.b.dispatchSimpleEvent(this,'annotationChange');},getAllAnnotations:function(){return tr.b.dictionaryValues(this.annotationsByGuid_);},addUserFriendlyCategoryDriver:function(ufcd){this.userFriendlyCategoryDrivers_.push(ufcd);},getUserFriendlyCategoryFromEvent:function(event){for(var i=0;i<this.userFriendlyCategoryDrivers_.length;i++){var ufc=this.userFriendlyCategoryDrivers_[i].fromEvent(event);if(ufc!==undefined)return ufc;}return undefined;},findAllThreadsNamed:function(name){var namedThreads=[];namedThreads.push.apply(namedThreads,this.kernel.findAllThreadsNamed(name));for(var pid in this.processes){namedThreads.push.apply(namedThreads,this.processes[pid].findAllThreadsNamed(name));}return namedThreads;},get importOptions(){return this.importOptions_;},set importOptions(options){this.importOptions_=options;},get intrinsicTimeUnit(){if(this.intrinsicTimeUnit_===undefined)return tr.b.TimeDisplayModes.ms;return this.intrinsicTimeUnit_;},set intrinsicTimeUnit(value){if(this.intrinsicTimeUnit_===value)return;if(this.intrinsicTimeUnit_!==undefined)throw new Error('Intrinsic time unit already set');this.intrinsicTimeUnit_=value;},get isTimeHighResolution(){return this.isTimeHighResolution_;},set isTimeHighResolution(value){this.isTimeHighResolution_=value;},get canonicalUrl(){return this.canonicalUrl_;},set canonicalUrl(value){if(this.canonicalUrl_===value)return;if(this.canonicalUrl_!==undefined)throw new Error('canonicalUrl already set');this.canonicalUrl_=value;},importWarning:function(data){data.showToUser=!!data.showToUser;this.importWarnings_.push(data);if(this.reportedImportWarnings_[data.type]===true)return;if(this.importOptions_.showImportWarnings)console.warn(data.message);this.reportedImportWarnings_[data.type]=true;},get hasImportWarnings(){return this.importWarnings_.length>0;},get importWarnings(){return this.importWarnings_;},get importWarningsThatShouldBeShownToUser(){return this.importWarnings_.filter(function(warning){return warning.showToUser;});},autoCloseOpenSlices:function(){this.samples.sort(function(x,y){return x.start-y.start;});this.updateBounds();this.kernel.autoCloseOpenSlices();for(var pid in this.processes)this.processes[pid].autoCloseOpenSlices();},createSubSlices:function(){this.kernel.createSubSlices();for(var pid in this.processes)this.processes[pid].createSubSlices();},preInitializeObjects:function(){for(var pid in this.processes)this.processes[pid].preInitializeObjects();},initializeObjects:function(){for(var pid in this.processes)this.processes[pid].initializeObjects();},pruneEmptyContainers:function(){this.kernel.pruneEmptyContainers();for(var pid in this.processes)this.processes[pid].pruneEmptyContainers();},mergeKernelWithUserland:function(){for(var pid in this.processes)this.processes[pid].mergeKernelWithUserland();},computeWorldBounds:function(shiftWorldToZero){this.updateBounds();this.updateCategories_();if(shiftWorldToZero)this.shiftWorldToZero();},buildFlowEventIntervalTree:function(){for(var i=0;i<this.flowEvents.length;++i){var flowEvent=this.flowEvents[i];this.flowIntervalTree.insert(flowEvent);}this.flowIntervalTree.updateHighValues();},cleanupUndeletedObjects:function(){for(var pid in this.processes)this.processes[pid].autoDeleteObjects(this.bounds.max);},sortMemoryDumps:function(){this.globalMemoryDumps.sort(function(x,y){return x.start-y.start;});for(var pid in this.processes)this.processes[pid].sortMemoryDumps();},finalizeMemoryGraphs:function(){this.globalMemoryDumps.forEach(function(dump){dump.finalizeGraph();});},buildEventIndices:function(){this.modelIndices=new tr.model.ModelIndices(this);},sortAlerts:function(){this.alerts.sort(function(x,y){return x.start-y.start;});},applyObjectRefPatchups:function(){var unresolved=[];this.patchupsToApply_.forEach(function(patchup){if(patchup.pidRef in this.processes){var snapshot=this.processes[patchup.pidRef].objects.getSnapshotAt(patchup.scopedId,patchup.ts);if(snapshot){patchup.object[patchup.field]=snapshot;snapshot.referencedAt(patchup.item,patchup.object,patchup.field);return;}}unresolved.push(patchup);},this);this.patchupsToApply_=unresolved;},replacePIDRefsInPatchups:function(oldPidRef,newPidRef){this.patchupsToApply_.forEach(function(patchup){if(patchup.pidRef===oldPidRef){patchup.pidRef=newPidRef;}});},joinRefs:function(){this.joinObjectRefs_();this.applyObjectRefPatchups();},joinObjectRefs_:function(){tr.b.iterItems(this.processes,function(pid,process){this.joinObjectRefsForProcess_(pid,process);},this);},joinObjectRefsForProcess_:function(pid,process){tr.b.iterItems(process.threads,function(tid,thread){thread.asyncSliceGroup.slices.forEach(function(item){this.searchItemForIDRefs_(pid,'start',item);},this);thread.sliceGroup.slices.forEach(function(item){this.searchItemForIDRefs_(pid,'start',item);},this);},this);process.objects.iterObjectInstances(function(instance){instance.snapshots.forEach(function(item){this.searchItemForIDRefs_(pid,'ts',item);},this);},this);},searchItemForIDRefs_:function(pid,itemTimestampField,item){if(!item.args&&!item.contexts)return;var patchupsToApply=this.patchupsToApply_;function handleField(object,fieldName,fieldValue){if(!fieldValue||!fieldValue.id_ref&&!fieldValue.idRef)return;var scope=fieldValue.scope||tr.model.OBJECT_DEFAULT_SCOPE;var idRef=fieldValue.id_ref||fieldValue.idRef;var scopedId=new tr.model.ScopedId(scope,idRef);var pidRef=fieldValue.pid_ref||fieldValue.pidRef||pid;var ts=item[itemTimestampField];patchupsToApply.push({item:item,object:object,field:fieldName,pidRef:pidRef,scopedId:scopedId,ts:ts});}function iterObjectFieldsRecursively(object){if(!(object instanceof Object))return;if(object instanceof tr.model.ObjectSnapshot||object instanceof Float32Array||object instanceof tr.b.Quad)return;if(object instanceof Array){for(var i=0;i<object.length;i++){handleField(object,i,object[i]);iterObjectFieldsRecursively(object[i]);}return;}for(var key in object){var value=object[key];handleField(object,key,value);iterObjectFieldsRecursively(value);}}iterObjectFieldsRecursively(item.args);iterObjectFieldsRecursively(item.contexts);}};return{Model:Model};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/model_indices.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/model_indices.js

Statements: 33.33% (6 / 18)      Branches: 0% (0 / 8)      Functions: 20% (1 / 5)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){function ModelIndices(model){this.flowEventsById_={};model.flowEvents.forEach(function(fe){if(fe.id!==undefined){if(!this.flowEventsById_.hasOwnProperty(fe.id)){this.flowEventsById_[fe.id]=new Array();}this.flowEventsById_[fe.id].push(fe);}},this);}ModelIndices.prototype={addEventWithId:function(id,event){if(!this.flowEventsById_.hasOwnProperty(id)){this.flowEventsById_[id]=new Array();}this.flowEventsById_[id].push(event);},getFlowEventsWithId:function(id){if(!this.flowEventsById_.hasOwnProperty(id))return[];return this.flowEventsById_[id];}};return{ModelIndices:ModelIndices};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/model_stats.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/model_stats.js

Statements: 18.75% (6 / 32)      Branches: 0% (0 / 6)      Functions: 16.67% (1 / 6)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/unit.js");'use strict';global.tr.exportTo('tr.model',function(){function ModelStats(){this.traceEventCountsByKey_=new Map();this.allTraceEventStats_=[];this.traceEventStatsInTimeIntervals_=new Map();this.allTraceEventStatsInTimeIntervals_=[];this.hasEventSizesinBytes_=false;}ModelStats.prototype={TIME_INTERVAL_SIZE_IN_MS:100,willProcessBasicTraceEvent:function(phase,category,title,ts,opt_eventSizeinBytes){var key=phase+'/'+category+'/'+title;var eventStats=this.traceEventCountsByKey_.get(key);if(eventStats===undefined){eventStats={phase:phase,category:category,title:title,numEvents:0,totalEventSizeinBytes:0};this.traceEventCountsByKey_.set(key,eventStats);this.allTraceEventStats_.push(eventStats);}eventStats.numEvents++;var timeIntervalKey=Math.floor(tr.b.Unit.timestampFromUs(ts)/this.TIME_INTERVAL_SIZE_IN_MS);var eventStatsByTimeInverval=this.traceEventStatsInTimeIntervals_.get(timeIntervalKey);if(eventStatsByTimeInverval===undefined){eventStatsByTimeInverval={timeInterval:timeIntervalKey,numEvents:0,totalEventSizeinBytes:0};this.traceEventStatsInTimeIntervals_.set(timeIntervalKey,eventStatsByTimeInverval);this.allTraceEventStatsInTimeIntervals_.push(eventStatsByTimeInverval);}eventStatsByTimeInverval.numEvents++;if(opt_eventSizeinBytes!==undefined){this.hasEventSizesinBytes_=true;eventStats.totalEventSizeinBytes+=opt_eventSizeinBytes;eventStatsByTimeInverval.totalEventSizeinBytes+=opt_eventSizeinBytes;}},get allTraceEventStats(){return this.allTraceEventStats_;},get allTraceEventStatsInTimeIntervals(){return this.allTraceEventStatsInTimeIntervals_;},get hasEventSizesinBytes(){return this.hasEventSizesinBytes_;}};return{ModelStats:ModelStats};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/object_collection.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/object_collection.js

Statements: 12.62% (13 / 103)      Branches: 0% (0 / 30)      Functions: 3.13% (1 / 32)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/range.js");require("../base/sorted_array_utils.js");require("../base/utils.js");require("./event_container.js");require("./object_instance.js");require("./time_to_object_instance_map.js");'use strict';global.tr.exportTo('tr.model',function(){var ObjectInstance=tr.model.ObjectInstance;var ObjectSnapshot=tr.model.ObjectSnapshot;function ObjectCollection(parent){tr.model.EventContainer.call(this);this.parent=parent;this.instanceMapsByScopedId_={};this.instancesByTypeName_={};this.createObjectInstance_=this.createObjectInstance_.bind(this);}ObjectCollection.prototype={__proto__:tr.model.EventContainer.prototype,childEvents:function*(){for(var instance of this.getAllObjectInstances()){yield instance;yield*instance.snapshots;}},createObjectInstance_:function(parent,scopedId,category,name,creationTs,opt_baseTypeName){var constructor=tr.model.ObjectInstance.subTypes.getConstructor(category,name);var instance=new constructor(parent,scopedId,category,name,creationTs,opt_baseTypeName);var typeName=instance.typeName;var instancesOfTypeName=this.instancesByTypeName_[typeName];if(!instancesOfTypeName){instancesOfTypeName=[];this.instancesByTypeName_[typeName]=instancesOfTypeName;}instancesOfTypeName.push(instance);return instance;},getOrCreateInstanceMap_:function(scopedId){var dict;if(scopedId.scope in this.instanceMapsByScopedId_){dict=this.instanceMapsByScopedId_[scopedId.scope];}else{dict={};this.instanceMapsByScopedId_[scopedId.scope]=dict;}var instanceMap=dict[scopedId.id];if(instanceMap)return instanceMap;instanceMap=new tr.model.TimeToObjectInstanceMap(this.createObjectInstance_,this.parent,scopedId);dict[scopedId.id]=instanceMap;return instanceMap;},idWasCreated:function(scopedId,category,name,ts){var instanceMap=this.getOrCreateInstanceMap_(scopedId);return instanceMap.idWasCreated(category,name,ts);},addSnapshot:function(scopedId,category,name,ts,args,opt_baseTypeName){var instanceMap=this.getOrCreateInstanceMap_(scopedId);var snapshot=instanceMap.addSnapshot(category,name,ts,args,opt_baseTypeName);if(snapshot.objectInstance.category!=category){var msg='Added snapshot name='+name+' with cat='+category+' impossible. It instance was created/snapshotted with cat='+snapshot.objectInstance.category+' name='+snapshot.objectInstance.name;throw new Error(msg);}if(opt_baseTypeName&&snapshot.objectInstance.baseTypeName!=opt_baseTypeName){throw new Error('Could not add snapshot with baseTypeName='+opt_baseTypeName+'. It '+'was previously created with name='+snapshot.objectInstance.baseTypeName);}if(snapshot.objectInstance.name!=name){throw new Error('Could not add snapshot with name='+name+'. It '+'was previously created with name='+snapshot.objectInstance.name);}return snapshot;},idWasDeleted:function(scopedId,category,name,ts){var instanceMap=this.getOrCreateInstanceMap_(scopedId);var deletedInstance=instanceMap.idWasDeleted(category,name,ts);if(!deletedInstance)return;if(deletedInstance.category!=category){var msg='Deleting object '+deletedInstance.name+' with a different category '+'than when it was created. It previous had cat='+deletedInstance.category+' but the delete command '+'had cat='+category;throw new Error(msg);}if(deletedInstance.baseTypeName!=name){throw new Error('Deletion requested for name='+name+' could not proceed: '+'An existing object with baseTypeName='+deletedInstance.baseTypeName+' existed.');}},autoDeleteObjects:function(maxTimestamp){tr.b.iterItems(this.instanceMapsByScopedId_,function(scope,imapById){tr.b.iterItems(imapById,function(id,i2imap){var lastInstance=i2imap.lastInstance;if(lastInstance.deletionTs!=Number.MAX_VALUE)return;i2imap.idWasDeleted(lastInstance.category,lastInstance.name,maxTimestamp);lastInstance.deletionTsWasExplicit=false;});});},getObjectInstanceAt:function(scopedId,ts){var instanceMap;if(scopedId.scope in this.instanceMapsByScopedId_)instanceMap=this.instanceMapsByScopedId_[scopedId.scope][scopedId.id];if(!instanceMap)return undefined;return instanceMap.getInstanceAt(ts);},getSnapshotAt:function(scopedId,ts){var instance=this.getObjectInstanceAt(scopedId,ts);if(!instance)return undefined;return instance.getSnapshotAt(ts);},iterObjectInstances:function(iter,opt_this){opt_this=opt_this||this;tr.b.iterItems(this.instanceMapsByScopedId_,function(scope,imapById){tr.b.iterItems(imapById,function(id,i2imap){i2imap.instances.forEach(iter,opt_this);});});},getAllObjectInstances:function(){var instances=[];this.iterObjectInstances(function(i){instances.push(i);});return instances;},getAllInstancesNamed:function(name){return this.instancesByTypeName_[name];},getAllInstancesByTypeName:function(){return this.instancesByTypeName_;},preInitializeAllObjects:function(){this.iterObjectInstances(function(instance){instance.preInitialize();});},initializeAllObjects:function(){this.iterObjectInstances(function(instance){instance.initialize();});},initializeInstances:function(){this.iterObjectInstances(function(instance){instance.initialize();});},updateBounds:function(){this.bounds.reset();this.iterObjectInstances(function(instance){instance.updateBounds();this.bounds.addRange(instance.bounds);},this);},shiftTimestampsForward:function(amount){this.iterObjectInstances(function(instance){instance.shiftTimestampsForward(amount);});},addCategoriesToDict:function(categoriesDict){this.iterObjectInstances(function(instance){categoriesDict[instance.category]=true;});}};return{ObjectCollection:ObjectCollection};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/object_instance.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/object_instance.js

Statements: 11.83% (11 / 93)      Branches: 0% (0 / 48)      Functions: 6.25% (1 / 16)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/range.js");require("../base/sorted_array_utils.js");require("./event.js");require("./object_snapshot.js");'use strict';global.tr.exportTo('tr.model',function(){var ObjectSnapshot=tr.model.ObjectSnapshot;function ObjectInstance(parent,scopedId,category,name,creationTs,opt_baseTypeName){tr.model.Event.call(this);this.parent=parent;this.scopedId=scopedId;this.category=category;this.baseTypeName=opt_baseTypeName?opt_baseTypeName:name;this.name=name;this.creationTs=creationTs;this.creationTsWasExplicit=false;this.deletionTs=Number.MAX_VALUE;this.deletionTsWasExplicit=false;this.colorId=0;this.bounds=new tr.b.Range();this.snapshots=[];this.hasImplicitSnapshots=false;}ObjectInstance.prototype={__proto__:tr.model.Event.prototype,get typeName(){return this.name;},addBoundsToRange:function(range){range.addRange(this.bounds);},addSnapshot:function(ts,args,opt_name,opt_baseTypeName){if(ts<this.creationTs)throw new Error('Snapshots must be >= instance.creationTs');if(ts>=this.deletionTs)throw new Error('Snapshots cannot be added after '+'an objects deletion timestamp.');var lastSnapshot;if(this.snapshots.length>0){lastSnapshot=this.snapshots[this.snapshots.length-1];if(lastSnapshot.ts==ts)throw new Error('Snapshots already exists at this time!');if(ts<lastSnapshot.ts){throw new Error('Snapshots must be added in increasing timestamp order');}}if(opt_name&&this.name!=opt_name){if(!opt_baseTypeName)throw new Error('Must provide base type name for name update');if(this.baseTypeName!=opt_baseTypeName)throw new Error('Cannot update type name: base types dont match');this.name=opt_name;}var snapshotConstructor=tr.model.ObjectSnapshot.subTypes.getConstructor(this.category,this.name);var snapshot=new snapshotConstructor(this,ts,args);this.snapshots.push(snapshot);return snapshot;},wasDeleted:function(ts){var lastSnapshot;if(this.snapshots.length>0){lastSnapshot=this.snapshots[this.snapshots.length-1];if(lastSnapshot.ts>ts)throw new Error('Instance cannot be deleted at ts='+ts+'. A snapshot exists that is older.');}this.deletionTs=ts;this.deletionTsWasExplicit=true;},preInitialize:function(){for(var i=0;i<this.snapshots.length;i++)this.snapshots[i].preInitialize();},initialize:function(){for(var i=0;i<this.snapshots.length;i++)this.snapshots[i].initialize();},isAliveAt:function(ts){if(ts<this.creationTs&&this.creationTsWasExplicit)return false;if(ts>this.deletionTs)return false;return true;},getSnapshotAt:function(ts){if(ts<this.creationTs){if(this.creationTsWasExplicit)throw new Error('ts must be within lifetime of this instance');return this.snapshots[0];}if(ts>this.deletionTs)throw new Error('ts must be within lifetime of this instance');var snapshots=this.snapshots;var i=tr.b.findIndexInSortedIntervals(snapshots,function(snapshot){return snapshot.ts;},function(snapshot,i){if(i==snapshots.length-1)return snapshots[i].objectInstance.deletionTs;return snapshots[i+1].ts-snapshots[i].ts;},ts);if(i<0){return this.snapshots[0];}if(i>=this.snapshots.length)return this.snapshots[this.snapshots.length-1];return this.snapshots[i];},updateBounds:function(){this.bounds.reset();this.bounds.addValue(this.creationTs);if(this.deletionTs!=Number.MAX_VALUE)this.bounds.addValue(this.deletionTs);else if(this.snapshots.length>0)this.bounds.addValue(this.snapshots[this.snapshots.length-1].ts);},shiftTimestampsForward:function(amount){this.creationTs+=amount;if(this.deletionTs!=Number.MAX_VALUE)this.deletionTs+=amount;this.snapshots.forEach(function(snapshot){snapshot.ts+=amount;});},get userFriendlyName(){return this.typeName+' object '+this.scopedId;}};tr.model.EventRegistry.register(ObjectInstance,{name:'objectInstance',pluralName:'objectInstances'});return{ObjectInstance:ObjectInstance};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/object_snapshot.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/object_snapshot.js

Statements: 57.14% (8 / 14)      Branches: 100% (0 / 0)      Functions: 14.29% (1 / 7)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/unit.js");require("./event.js");'use strict';global.tr.exportTo('tr.model',function(){function ObjectSnapshot(objectInstance,ts,args){tr.model.Event.call(this);this.objectInstance=objectInstance;this.ts=ts;this.args=args;}ObjectSnapshot.prototype={__proto__:tr.model.Event.prototype,preInitialize:function(){},initialize:function(){},referencedAt:function(item,object,field){},addBoundsToRange:function(range){range.addValue(this.ts);},get userFriendlyName(){return'Snapshot of '+this.objectInstance.typeName+' '+this.objectInstance.id+' @ '+tr.b.Unit.byName.timeStampInMs.format(this.ts);}};tr.model.EventRegistry.register(ObjectSnapshot,{name:'objectSnapshot',pluralName:'objectSnapshots'});return{ObjectSnapshot:ObjectSnapshot};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/power_sample.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/power_sample.js

Statements: 50% (10 / 20)      Branches: 100% (0 / 0)      Functions: 12.5% (1 / 8)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./event.js");require("./event_registry.js");'use strict';global.tr.exportTo('tr.model',function(){var Event=tr.model.Event;var EventRegistry=tr.model.EventRegistry;function PowerSample(series,start,powerInW){Event.call(this);this.series_=series;this.start_=start;this.powerInW_=powerInW;}PowerSample.prototype={__proto__:Event.prototype,get series(){return this.series_;},get start(){return this.start_;},set start(value){this.start_=value;},get powerInW(){return this.powerInW_;},set powerInW(value){this.powerInW_=value;},addBoundsToRange:function(range){range.addValue(this.start);}};EventRegistry.register(PowerSample,{name:'powerSample',pluralName:'powerSamples'});return{PowerSample:PowerSample};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/power_series.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/power_series.js

Statements: 21.57% (11 / 51)      Branches: 0% (0 / 6)      Functions: 9.09% (1 / 11)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/range.js");require("../base/sorted_array_utils.js");require("../base/unit_scale.js");require("./event_container.js");require("./power_sample.js");'use strict';global.tr.exportTo('tr.model',function(){var PowerSample=tr.model.PowerSample;function PowerSeries(device){tr.model.EventContainer.call(this);this.device_=device;this.samples_=[];}PowerSeries.prototype={__proto__:tr.model.EventContainer.prototype,get device(){return this.device_;},get samples(){return this.samples_;},get stableId(){return this.device_.stableId+'.PowerSeries';},addPowerSample:function(ts,val){var sample=new PowerSample(this,ts,val);this.samples_.push(sample);return sample;},getEnergyConsumedInJ:function(start,end){var measurementRange=tr.b.Range.fromExplicitRange(start,end);var energyConsumedInJ=0;var startIndex=tr.b.findLowIndexInSortedArray(this.samples,x=>x.start,start)-1;var endIndex=tr.b.findLowIndexInSortedArray(this.samples,x=>x.start,end);if(startIndex<0)startIndex=0;for(var i=startIndex;i<endIndex;i++){var sample=this.samples[i];var nextSample=this.samples[i+1];var sampleRange=new tr.b.Range();sampleRange.addValue(sample.start);sampleRange.addValue(nextSample?nextSample.start:sample.start);var intersectionRangeInMs=measurementRange.findIntersection(sampleRange);var durationInS=tr.b.convertUnit(intersectionRangeInMs.duration,tr.b.UnitScale.Metric.MILLI,tr.b.UnitScale.Metric.NONE);energyConsumedInJ+=durationInS*sample.powerInW;}return energyConsumedInJ;},getSamplesWithinRange:function(start,end){var startIndex=tr.b.findLowIndexInSortedArray(this.samples,x=>x.start,start);var endIndex=tr.b.findLowIndexInSortedArray(this.samples,x=>x.start,end);return this.samples.slice(startIndex,endIndex);},shiftTimestampsForward:function(amount){for(var i=0;i<this.samples_.length;++i)this.samples_[i].start+=amount;},updateBounds:function(){this.bounds.reset();if(this.samples_.length===0)return;this.bounds.addValue(this.samples_[0].start);this.bounds.addValue(this.samples_[this.samples_.length-1].start);},childEvents:function*(){yield*this.samples_;}};return{PowerSeries:PowerSeries};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/process.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/process.js

Statements: 15% (12 / 80)      Branches: 0% (0 / 22)      Functions: 6.25% (1 / 16)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./process_base.js");require("./process_memory_dump.js");'use strict';global.tr.exportTo('tr.model',function(){var ProcessBase=tr.model.ProcessBase;var ProcessInstantEvent=tr.model.ProcessInstantEvent;var Frame=tr.model.Frame;var ProcessMemoryDump=tr.model.ProcessMemoryDump;function Process(model,pid){if(model===undefined)throw new Error('model must be provided');if(pid===undefined)throw new Error('pid must be provided');tr.model.ProcessBase.call(this,model);this.pid=pid;this.name=undefined;this.labels=[];this.instantEvents=[];this.memoryDumps=[];this.frames=[];this.activities=[];};Process.compare=function(x,y){var tmp=tr.model.ProcessBase.compare(x,y);if(tmp)return tmp;tmp=tr.b.comparePossiblyUndefinedValues(x.name,y.name,function(x,y){return x.localeCompare(y);});if(tmp)return tmp;tmp=tr.b.compareArrays(x.labels,y.labels,function(x,y){return x.localeCompare(y);});if(tmp)return tmp;return x.pid-y.pid;};Process.prototype={__proto__:tr.model.ProcessBase.prototype,get stableId(){return this.pid;},compareTo:function(that){return Process.compare(this,that);},childEvents:function*(){yield*ProcessBase.prototype.childEvents.call(this);yield*this.instantEvents;yield*this.frames;yield*this.memoryDumps;},addLabelIfNeeded:function(labelName){for(var i=0;i<this.labels.length;i++){if(this.labels[i]===labelName)return;}this.labels.push(labelName);},get userFriendlyName(){var res;if(this.name)res=this.name+' (pid '+this.pid+')';else res='Process '+this.pid;if(this.labels.length)res+=': '+this.labels.join(', ');return res;},get userFriendlyDetails(){if(this.name)return this.name+' (pid '+this.pid+')';return'pid: '+this.pid;},getSettingsKey:function(){if(!this.name)return undefined;if(!this.labels.length)return'processes.'+this.name;return'processes.'+this.name+'.'+this.labels.join('.');},shiftTimestampsForward:function(amount){for(var i=0;i<this.instantEvents.length;i++)this.instantEvents[i].start+=amount;for(var i=0;i<this.frames.length;i++)this.frames[i].shiftTimestampsForward(amount);for(var i=0;i<this.memoryDumps.length;i++)this.memoryDumps[i].shiftTimestampsForward(amount);for(var i=0;i<this.activities.length;i++)this.activities[i].shiftTimestampsForward(amount);tr.model.ProcessBase.prototype.shiftTimestampsForward.apply(this,arguments);},updateBounds:function(){tr.model.ProcessBase.prototype.updateBounds.apply(this);for(var i=0;i<this.frames.length;i++)this.frames[i].addBoundsToRange(this.bounds);for(var i=0;i<this.memoryDumps.length;i++)this.memoryDumps[i].addBoundsToRange(this.bounds);for(var i=0;i<this.activities.length;i++)this.activities[i].addBoundsToRange(this.bounds);},sortMemoryDumps:function(){this.memoryDumps.sort(function(x,y){return x.start-y.start;});tr.model.ProcessMemoryDump.hookUpMostRecentVmRegionsLinks(this.memoryDumps);}};return{Process:Process};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/process_base.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/process_base.js

Statements: 15.05% (14 / 93)      Branches: 0% (0 / 16)      Functions: 4% (1 / 25)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/guid.js");require("../base/range.js");require("./counter.js");require("./event_container.js");require("./object_collection.js");require("./thread.js");'use strict';global.tr.exportTo('tr.model',function(){var Thread=tr.model.Thread;var Counter=tr.model.Counter;function ProcessBase(model){if(!model)throw new Error('Must provide a model');tr.model.EventContainer.call(this);this.model=model;this.threads={};this.counters={};this.objects=new tr.model.ObjectCollection(this);this.sortIndex=0;};ProcessBase.compare=function(x,y){return x.sortIndex-y.sortIndex;};ProcessBase.prototype={__proto__:tr.model.EventContainer.prototype,get stableId(){throw new Error('Not implemented');},childEventContainers:function*(){yield*tr.b.dictionaryValues(this.threads);yield*tr.b.dictionaryValues(this.counters);yield this.objects;},iterateAllPersistableObjects:function(cb){cb(this);for(var tid in this.threads)this.threads[tid].iterateAllPersistableObjects(cb);},get numThreads(){var n=0;for(var p in this.threads){n++;}return n;},shiftTimestampsForward:function(amount){for(var child of this.childEventContainers())child.shiftTimestampsForward(amount);},autoCloseOpenSlices:function(){for(var tid in this.threads){var thread=this.threads[tid];thread.autoCloseOpenSlices();}},autoDeleteObjects:function(maxTimestamp){this.objects.autoDeleteObjects(maxTimestamp);},preInitializeObjects:function(){this.objects.preInitializeAllObjects();},initializeObjects:function(){this.objects.initializeAllObjects();},mergeKernelWithUserland:function(){for(var tid in this.threads){var thread=this.threads[tid];thread.mergeKernelWithUserland();}},updateBounds:function(){this.bounds.reset();for(var tid in this.threads){this.threads[tid].updateBounds();this.bounds.addRange(this.threads[tid].bounds);}for(var id in this.counters){this.counters[id].updateBounds();this.bounds.addRange(this.counters[id].bounds);}this.objects.updateBounds();this.bounds.addRange(this.objects.bounds);},addCategoriesToDict:function(categoriesDict){for(var tid in this.threads)this.threads[tid].addCategoriesToDict(categoriesDict);for(var id in this.counters)categoriesDict[this.counters[id].category]=true;this.objects.addCategoriesToDict(categoriesDict);},findAllThreadsMatching:function(predicate,opt_this){var threads=[];for(var tid in this.threads){var thread=this.threads[tid];if(predicate.call(opt_this,thread))threads.push(thread);}return threads;},findAllThreadsNamed:function(name){var threads=this.findAllThreadsMatching(function(thread){if(!thread.name)return false;return thread.name===name;});return threads;},findAtMostOneThreadNamed:function(name){var threads=this.findAllThreadsNamed(name);if(threads.length===0)return undefined;if(threads.length>1)throw new Error('Expected no more than one '+name);return threads[0];},pruneEmptyContainers:function(){var threadsToKeep={};for(var tid in this.threads){var thread=this.threads[tid];if(!thread.isEmpty)threadsToKeep[tid]=thread;}this.threads=threadsToKeep;},getThread:function(tid){return this.threads[tid];},getOrCreateThread:function(tid){if(!this.threads[tid])this.threads[tid]=new Thread(this,tid);return this.threads[tid];},getOrCreateCounter:function(cat,name){var id=cat+'.'+name;if(!this.counters[id])this.counters[id]=new Counter(this,id,cat,name);return this.counters[id];},getSettingsKey:function(){throw new Error('Not implemented');},createSubSlices:function(){for(var tid in this.threads)this.threads[tid].createSubSlices();}};return{ProcessBase:ProcessBase};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/process_memory_dump.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/process_memory_dump.js

Statements: 16% (16 / 100)      Branches: 0% (0 / 47)      Functions: 8.33% (1 / 12)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/unit.js");require("./container_memory_dump.js");require("./memory_allocator_dump.js");require("./vm_region.js");'use strict';global.tr.exportTo('tr.model',function(){var DISCOUNTED_ALLOCATOR_NAMES=['winheap','malloc'];var TRACING_OVERHEAD_PATH=['allocated_objects','tracing_overhead'];var SIZE_NUMERIC_NAME=tr.model.MemoryAllocatorDump.SIZE_NUMERIC_NAME;var RESIDENT_SIZE_NUMERIC_NAME=tr.model.MemoryAllocatorDump.RESIDENT_SIZE_NUMERIC_NAME;function getSizeNumericValue(dump,sizeNumericName){var sizeNumeric=dump.numerics[sizeNumericName];if(sizeNumeric===undefined)return 0;return sizeNumeric.value;}function ProcessMemoryDump(globalMemoryDump,process,start){tr.model.ContainerMemoryDump.call(this,start);this.process=process;this.globalMemoryDump=globalMemoryDump;this.totals=undefined;this.vmRegions=undefined;this.heapDumps=undefined;this.tracingOverheadOwnershipSetUp_=false;this.tracingOverheadDiscountedFromVmRegions_=false;}ProcessMemoryDump.prototype={__proto__:tr.model.ContainerMemoryDump.prototype,get userFriendlyName(){return'Process memory dump at '+tr.b.Unit.byName.timeStampInMs.format(this.start);},get containerName(){return this.process.userFriendlyName;},get processMemoryDumps(){var dumps={};dumps[this.process.pid]=this;return dumps;},get hasOwnVmRegions(){return this.vmRegions!==undefined;},setUpTracingOverheadOwnership:function(opt_model){if(this.tracingOverheadOwnershipSetUp_)return;this.tracingOverheadOwnershipSetUp_=true;var tracingDump=this.getMemoryAllocatorDumpByFullName('tracing');if(tracingDump===undefined||tracingDump.owns!==undefined){return;}if(tracingDump.owns!==undefined)return;var hasDiscountedFromAllocatorDumps=DISCOUNTED_ALLOCATOR_NAMES.some(function(allocatorName){var allocatorDump=this.getMemoryAllocatorDumpByFullName(allocatorName);if(allocatorDump===undefined)return false;var nextPathIndex=0;var currentDump=allocatorDump;var currentFullName=allocatorName;for(;nextPathIndex<TRACING_OVERHEAD_PATH.length;nextPathIndex++){var childFullName=currentFullName+'/'+TRACING_OVERHEAD_PATH[nextPathIndex];var childDump=this.getMemoryAllocatorDumpByFullName(childFullName);if(childDump===undefined)break;currentDump=childDump;currentFullName=childFullName;}for(;nextPathIndex<TRACING_OVERHEAD_PATH.length;nextPathIndex++){var childFullName=currentFullName+'/'+TRACING_OVERHEAD_PATH[nextPathIndex];var childDump=new tr.model.MemoryAllocatorDump(currentDump.containerMemoryDump,childFullName);childDump.parent=currentDump;currentDump.children.push(childDump);currentFullName=childFullName;currentDump=childDump;}var ownershipLink=new tr.model.MemoryAllocatorDumpLink(tracingDump,currentDump);tracingDump.owns=ownershipLink;currentDump.ownedBy.push(ownershipLink);return true;},this);if(hasDiscountedFromAllocatorDumps)this.forceRebuildingMemoryAllocatorDumpByFullNameIndex();},discountTracingOverheadFromVmRegions:function(opt_model){if(this.tracingOverheadDiscountedFromVmRegions_)return;this.tracingOverheadDiscountedFromVmRegions_=true;var tracingDump=this.getMemoryAllocatorDumpByFullName('tracing');if(tracingDump===undefined)return;var discountedSize=getSizeNumericValue(tracingDump,SIZE_NUMERIC_NAME);var discountedResidentSize=getSizeNumericValue(tracingDump,RESIDENT_SIZE_NUMERIC_NAME);if(discountedSize<=0&&discountedResidentSize<=0)return;if(this.totals!==undefined){if(this.totals.residentBytes!==undefined)this.totals.residentBytes-=discountedResidentSize;if(this.totals.peakResidentBytes!==undefined)this.totals.peakResidentBytes-=discountedResidentSize;}if(this.vmRegions!==undefined){var hasSizeInBytes=this.vmRegions.sizeInBytes!==undefined;var hasPrivateDirtyResident=this.vmRegions.byteStats.privateDirtyResident!==undefined;var hasProportionalResident=this.vmRegions.byteStats.proportionalResident!==undefined;if(hasSizeInBytes&&discountedSize>0||(hasPrivateDirtyResident||hasProportionalResident)&&discountedResidentSize>0){var byteStats={};if(hasPrivateDirtyResident)byteStats.privateDirtyResident=-discountedResidentSize;if(hasProportionalResident)byteStats.proportionalResident=-discountedResidentSize;this.vmRegions.addRegion(tr.model.VMRegion.fromDict({mappedFile:'[discounted tracing overhead]',sizeInBytes:hasSizeInBytes?-discountedSize:undefined,byteStats:byteStats}));}}}};ProcessMemoryDump.hookUpMostRecentVmRegionsLinks=function(processDumps){var mostRecentVmRegions=undefined;processDumps.forEach(function(processDump){if(processDump.vmRegions!==undefined)mostRecentVmRegions=processDump.vmRegions;processDump.mostRecentVmRegions=mostRecentVmRegions;});};tr.model.EventRegistry.register(ProcessMemoryDump,{name:'processMemoryDump',pluralName:'processMemoryDumps'});return{ProcessMemoryDump:ProcessMemoryDump};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/rect_annotation.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/rect_annotation.js

Statements: 45.45% (10 / 22)      Branches: 100% (0 / 0)      Functions: 14.29% (1 / 7)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./location.js");require("./annotation.js");require("../ui/annotations/rect_annotation_view.js");'use strict';global.tr.exportTo('tr.model',function(){function RectAnnotation(start,end){tr.model.Annotation.apply(this,arguments);this.startLocation_=start;this.endLocation_=end;this.fillStyle='rgba(255, 180, 0, 0.3)';}RectAnnotation.fromDict=function(dict){var args=dict.args;var startLoc=new tr.model.Location(args.start.xWorld,args.start.yComponents);var endLoc=new tr.model.Location(args.end.xWorld,args.end.yComponents);return new tr.model.RectAnnotation(startLoc,endLoc);};RectAnnotation.prototype={__proto__:tr.model.Annotation.prototype,get startLocation(){return this.startLocation_;},get endLocation(){return this.endLocation_;},toDict:function(){return{typeName:'rect',args:{start:this.startLocation.toDict(),end:this.endLocation.toDict()}};},createView_:function(viewport){return new tr.ui.annotations.RectAnnotationView(viewport,this);}};tr.model.Annotation.register(RectAnnotation,{typeName:'rect'});return{RectAnnotation:RectAnnotation};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/sample.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/sample.js

Statements: 42.11% (8 / 19)      Branches: 0% (0 / 2)      Functions: 16.67% (1 / 6)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/unit.js");require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){function Sample(cpu,thread,title,start,leafStackFrame,opt_weight,opt_args){tr.model.TimedEvent.call(this,start);this.title=title;this.cpu=cpu;this.thread=thread;this.leafStackFrame=leafStackFrame;this.weight=opt_weight;this.args=opt_args||{};}Sample.prototype={__proto__:tr.model.TimedEvent.prototype,get colorId(){return this.leafStackFrame.colorId;},get stackTrace(){return this.leafStackFrame.stackTrace;},getUserFriendlyStackTrace:function(){return this.leafStackFrame.getUserFriendlyStackTrace();},get userFriendlyName(){return'Sample at '+tr.b.Unit.byName.timeStampInMs.format(this.start);}};tr.model.EventRegistry.register(Sample,{name:'sample',pluralName:'samples'});return{Sample:Sample};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/scoped_id.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/scoped_id.js

Statements: 58.33% (7 / 12)      Branches: 0% (0 / 2)      Functions: 33.33% (1 / 3)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");require("./constants.js");'use strict';global.tr.exportTo('tr.model',function(){function ScopedId(scope,id){if(scope===undefined){throw new Error('Scope should be defined. Use \''+tr.model.OBJECT_DEFAULT_SCOPE+'\' as the default scope.');}this.scope=scope;this.id=id;}ScopedId.prototype={toString:function(){return'{scope: '+this.scope+', id: '+this.id+'}';}};return{ScopedId:ScopedId};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/selectable_item.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/selectable_item.js

Statements: 38.89% (7 / 18)      Branches: 0% (0 / 4)      Functions: 16.67% (1 / 6)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./selection_state.js");'use strict';global.tr.exportTo('tr.model',function(){var SelectionState=tr.model.SelectionState;function SelectableItem(modelItem){this.modelItem_=modelItem;}SelectableItem.prototype={get modelItem(){return this.modelItem_;},get selected(){return this.selectionState===SelectionState.SELECTED;},addToSelection:function(selection){var modelItem=this.modelItem_;if(!modelItem)return;selection.push(modelItem);},addToTrackMap:function(eventToTrackMap,track){var modelItem=this.modelItem_;if(!modelItem)return;eventToTrackMap.addEvent(modelItem,track);}};return{SelectableItem:SelectableItem};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/selection_state.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/selection_state.js

Statements: 84.62% (11 / 13)      Branches: 100% (0 / 0)      Functions: 33.33% (1 / 3)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");require("../base/color_scheme.js");'use strict';global.tr.exportTo('tr.model',function(){var ColorScheme=tr.b.ColorScheme;var SelectionState={NONE:0,SELECTED:ColorScheme.properties.brightenedOffsets[0],HIGHLIGHTED:ColorScheme.properties.brightenedOffsets[1],DIMMED:ColorScheme.properties.dimmedOffsets[0],BRIGHTENED0:ColorScheme.properties.brightenedOffsets[0],BRIGHTENED1:ColorScheme.properties.brightenedOffsets[1],BRIGHTENED2:ColorScheme.properties.brightenedOffsets[2],DIMMED0:ColorScheme.properties.dimmedOffsets[0],DIMMED1:ColorScheme.properties.dimmedOffsets[1],DIMMED2:ColorScheme.properties.dimmedOffsets[2]};var brighteningLevels=[SelectionState.NONE,SelectionState.BRIGHTENED0,SelectionState.BRIGHTENED1,SelectionState.BRIGHTENED2];SelectionState.getFromBrighteningLevel=function(level){return brighteningLevels[level];};var dimmingLevels=[SelectionState.DIMMED0,SelectionState.DIMMED1,SelectionState.DIMMED2];SelectionState.getFromDimmingLevel=function(level){return dimmingLevels[level];};return{SelectionState:SelectionState};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/slice.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/slice.js

Statements: 6.31% (7 / 111)      Branches: 0% (0 / 28)      Functions: 4.55% (1 / 22)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/unit.js");require("./timed_event.js");'use strict';global.tr.exportTo('tr.model',function(){function Slice(category,title,colorId,start,args,opt_duration,opt_cpuStart,opt_cpuDuration,opt_argsStripped,opt_bindId){if(!(this instanceof Slice)){throw new Error("Can't instantiate pure virtual class Slice");}tr.model.TimedEvent.call(this,start);this.category=category||'';this.title=title;this.colorId=colorId;this.args=args;this.startStackFrame=undefined;this.endStackFrame=undefined;this.didNotFinish=false;this.inFlowEvents=[];this.outFlowEvents=[];this.subSlices=[];this.selfTime=undefined;this.cpuSelfTime=undefined;this.important=false;this.parentContainer=undefined;this.argsStripped=false;this.bind_id_=opt_bindId;this.parentSlice=undefined;this.isTopLevel=false;if(opt_duration!==undefined)this.duration=opt_duration;if(opt_cpuStart!==undefined)this.cpuStart=opt_cpuStart;if(opt_cpuDuration!==undefined)this.cpuDuration=opt_cpuDuration;if(opt_argsStripped!==undefined)this.argsStripped=true;}Slice.prototype={__proto__:tr.model.TimedEvent.prototype,get analysisTypeName(){return this.title;},get userFriendlyName(){return'Slice '+this.title+' at '+tr.b.Unit.byName.timeStampInMs.format(this.start);},get stableId(){var parentSliceGroup=this.parentContainer.sliceGroup;return parentSliceGroup.stableId+'.'+parentSliceGroup.slices.indexOf(this);},findDescendentSlice:function(targetTitle){if(!this.subSlices)return undefined;for(var i=0;i<this.subSlices.length;i++){if(this.subSlices[i].title==targetTitle)return this.subSlices[i];var slice=this.subSlices[i].findDescendentSlice(targetTitle);if(slice)return slice;}return undefined;},get mostTopLevelSlice(){var curSlice=this;while(curSlice.parentSlice)curSlice=curSlice.parentSlice;return curSlice;},getProcess:function(){var thread=this.parentContainer;if(thread&&thread.getProcess)return thread.getProcess();return undefined;},get model(){var process=this.getProcess();if(process!==undefined)return this.getProcess().model;return undefined;},findTopmostSlicesRelativeToThisSlice:function*(eventPredicate){if(eventPredicate(this)){yield this;return;}for(var s of this.subSlices)yield*s.findTopmostSlicesRelativeToThisSlice(eventPredicate);},iterateAllSubsequentSlices:function(callback,opt_this){var parentStack=[];var started=false;var topmostSlice=this.mostTopLevelSlice;parentStack.push(topmostSlice);while(parentStack.length!==0){var curSlice=parentStack.pop();if(started)callback.call(opt_this,curSlice);else started=curSlice.guid===this.guid;for(var i=curSlice.subSlices.length-1;i>=0;i--){parentStack.push(curSlice.subSlices[i]);}}},get subsequentSlices(){var res=[];this.iterateAllSubsequentSlices(function(subseqSlice){res.push(subseqSlice);});return res;},enumerateAllAncestors:function*(){var curSlice=this;while(curSlice.parentSlice){curSlice=curSlice.parentSlice;yield curSlice;}},get ancestorSlices(){var res=[];for(var slice of this.enumerateAllAncestors())res.push(slice);return res;},iterateEntireHierarchy:function(callback,opt_this){var mostTopLevelSlice=this.mostTopLevelSlice;callback.call(opt_this,mostTopLevelSlice);mostTopLevelSlice.iterateAllSubsequentSlices(callback,opt_this);},get entireHierarchy(){var res=[];this.iterateEntireHierarchy(function(slice){res.push(slice);});return res;},get ancestorAndSubsequentSlices(){var res=[];res.push(this);for(var aSlice of this.enumerateAllAncestors())res.push(aSlice);this.iterateAllSubsequentSlices(function(sSlice){res.push(sSlice);});return res;},enumerateAllDescendents:function*(){for(var slice of this.subSlices)yield slice;for(var slice of this.subSlices)yield*slice.enumerateAllDescendents();},get descendentSlices(){var res=[];for(var slice of this.enumerateAllDescendents())res.push(slice);return res;}};return{Slice:Slice};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/slice_group.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/slice_group.js

Statements: 5.86% (17 / 290)      Branches: 0% (0 / 137)      Functions: 2.27% (1 / 44)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/color_scheme.js");require("../base/guid.js");require("../base/sorted_array_utils.js");require("../core/filter.js");require("./event_container.js");require("./thread_slice.js");'use strict';global.tr.exportTo('tr.model',function(){var ColorScheme=tr.b.ColorScheme;var ThreadSlice=tr.model.ThreadSlice;function getSliceLo(s){return s.start;}function getSliceHi(s){return s.end;}function SliceGroup(parentContainer,opt_sliceConstructor,opt_name){tr.model.EventContainer.call(this);this.parentContainer_=parentContainer;var sliceConstructor=opt_sliceConstructor||ThreadSlice;this.sliceConstructor=sliceConstructor;this.sliceConstructorSubTypes=this.sliceConstructor.subTypes;if(!this.sliceConstructorSubTypes)throw new Error('opt_sliceConstructor must have a subtype registry.');this.openPartialSlices_=[];this.slices=[];this.topLevelSlices=[];this.haveTopLevelSlicesBeenBuilt=false;this.name_=opt_name;if(this.model===undefined)throw new Error('SliceGroup must have model defined.');}SliceGroup.prototype={__proto__:tr.model.EventContainer.prototype,get parentContainer(){return this.parentContainer_;},get model(){return this.parentContainer_.model;},get stableId(){return this.parentContainer_.stableId+'.SliceGroup';},getSettingsKey:function(){if(!this.name_)return undefined;var parentKey=this.parentContainer_.getSettingsKey();if(!parentKey)return undefined;return parentKey+'.'+this.name;},get length(){return this.slices.length;},pushSlice:function(slice){this.haveTopLevelSlicesBeenBuilt=false;slice.parentContainer=this.parentContainer_;this.slices.push(slice);return slice;},pushSlices:function(slices){this.haveTopLevelSlicesBeenBuilt=false;slices.forEach(function(slice){slice.parentContainer=this.parentContainer_;this.slices.push(slice);},this);},beginSlice:function(category,title,ts,opt_args,opt_tts,opt_argsStripped,opt_colorId){if(this.openPartialSlices_.length){var prevSlice=this.openPartialSlices_[this.openPartialSlices_.length-1];if(ts<prevSlice.start)throw new Error('Slices must be added in increasing timestamp order');}var colorId=opt_colorId||ColorScheme.getColorIdForGeneralPurposeString(title);var sliceConstructorSubTypes=this.sliceConstructorSubTypes;var sliceType=sliceConstructorSubTypes.getConstructor(category,title);var slice=new sliceType(category,title,colorId,ts,opt_args?opt_args:{},null,opt_tts,undefined,opt_argsStripped);this.openPartialSlices_.push(slice);slice.didNotFinish=true;this.pushSlice(slice);return slice;},isTimestampValidForBeginOrEnd:function(ts){if(!this.openPartialSlices_.length)return true;var top=this.openPartialSlices_[this.openPartialSlices_.length-1];return ts>=top.start;},get openSliceCount(){return this.openPartialSlices_.length;},get mostRecentlyOpenedPartialSlice(){if(!this.openPartialSlices_.length)return undefined;return this.openPartialSlices_[this.openPartialSlices_.length-1];},endSlice:function(ts,opt_tts,opt_colorId){if(!this.openSliceCount)throw new Error('endSlice called without an open slice');var slice=this.openPartialSlices_[this.openSliceCount-1];this.openPartialSlices_.splice(this.openSliceCount-1,1);if(ts<slice.start)throw new Error('Slice '+slice.title+' end time is before its start.');slice.duration=ts-slice.start;slice.didNotFinish=false;slice.colorId=opt_colorId||slice.colorId;if(opt_tts&&slice.cpuStart!==undefined)slice.cpuDuration=opt_tts-slice.cpuStart;return slice;},pushCompleteSlice:function(category,title,ts,duration,tts,cpuDuration,opt_args,opt_argsStripped,opt_colorId,opt_bindId){var colorId=opt_colorId||ColorScheme.getColorIdForGeneralPurposeString(title);var sliceConstructorSubTypes=this.sliceConstructorSubTypes;var sliceType=sliceConstructorSubTypes.getConstructor(category,title);var slice=new sliceType(category,title,colorId,ts,opt_args?opt_args:{},duration,tts,cpuDuration,opt_argsStripped,opt_bindId);if(duration===undefined)slice.didNotFinish=true;this.pushSlice(slice);return slice;},autoCloseOpenSlices:function(){this.updateBounds();var maxTimestamp=this.bounds.max;for(var sI=0;sI<this.slices.length;sI++){var slice=this.slices[sI];if(slice.didNotFinish)slice.duration=maxTimestamp-slice.start;}this.openPartialSlices_=[];},shiftTimestampsForward:function(amount){for(var sI=0;sI<this.slices.length;sI++){var slice=this.slices[sI];slice.start=slice.start+amount;}},updateBounds:function(){this.bounds.reset();for(var i=0;i<this.slices.length;i++){this.bounds.addValue(this.slices[i].start);this.bounds.addValue(this.slices[i].end);}},copySlice:function(slice){var sliceConstructorSubTypes=this.sliceConstructorSubTypes;var sliceType=sliceConstructorSubTypes.getConstructor(slice.category,slice.title);var newSlice=new sliceType(slice.category,slice.title,slice.colorId,slice.start,slice.args,slice.duration,slice.cpuStart,slice.cpuDuration);newSlice.didNotFinish=slice.didNotFinish;return newSlice;},findTopmostSlicesInThisContainer:function*(eventPredicate,opt_this){if(!this.haveTopLevelSlicesBeenBuilt)throw new Error('Nope');for(var s of this.topLevelSlices)yield*s.findTopmostSlicesRelativeToThisSlice(eventPredicate);},childEvents:function*(){yield*this.slices;},childEventContainers:function*(){},getSlicesOfName:function(title){var slices=[];for(var i=0;i<this.slices.length;i++){if(this.slices[i].title==title){slices.push(this.slices[i]);}}return slices;},iterSlicesInTimeRange:function(callback,start,end){var ret=[];tr.b.iterateOverIntersectingIntervals(this.topLevelSlices,function(s){return s.start;},function(s){return s.duration;},start,end,function(topLevelSlice){callback(topLevelSlice);for(var slice of topLevelSlice.enumerateAllDescendents())callback(slice);});return ret;},findFirstSlice:function(){if(!this.haveTopLevelSlicesBeenBuilt)throw new Error('Nope');if(0===this.slices.length)return undefined;return this.slices[0];},findSliceAtTs:function(ts){if(!this.haveTopLevelSlicesBeenBuilt)throw new Error('Nope');var i=tr.b.findIndexInSortedClosedIntervals(this.topLevelSlices,getSliceLo,getSliceHi,ts);if(i==-1||i==this.topLevelSlices.length)return undefined;var curSlice=this.topLevelSlices[i];while(true){var i=tr.b.findIndexInSortedClosedIntervals(curSlice.subSlices,getSliceLo,getSliceHi,ts);if(i==-1||i==curSlice.subSlices.length)return curSlice;curSlice=curSlice.subSlices[i];}},findNextSliceAfter:function(ts,refGuid){var i=tr.b.findLowIndexInSortedArray(this.slices,getSliceLo,ts);if(i===this.slices.length)return undefined;for(;i<this.slices.length;i++){var slice=this.slices[i];if(slice.start>ts)return slice;if(slice.guid<=refGuid)continue;return slice;}return undefined;},createSubSlices:function(){this.haveTopLevelSlicesBeenBuilt=true;this.createSubSlicesImpl_();if(this.parentContainer.timeSlices)this.addCpuTimeToSubslices_(this.parentContainer.timeSlices);this.slices.forEach(function(slice){var selfTime=slice.duration;for(var i=0;i<slice.subSlices.length;i++)selfTime-=slice.subSlices[i].duration;slice.selfTime=selfTime;if(slice.cpuDuration===undefined)return;var cpuSelfTime=slice.cpuDuration;for(var i=0;i<slice.subSlices.length;i++){if(slice.subSlices[i].cpuDuration!==undefined)cpuSelfTime-=slice.subSlices[i].cpuDuration;}slice.cpuSelfTime=cpuSelfTime;});},createSubSlicesImpl_:function(){var precisionUnit=this.model.intrinsicTimeUnit;function addSliceIfBounds(parent,child){if(parent.bounds(child,precisionUnit)){child.parentSlice=parent;if(parent.subSlices===undefined)parent.subSlices=[];parent.subSlices.push(child);return true;}return false;}if(!this.slices.length)return;var ops=[];for(var i=0;i<this.slices.length;i++){if(this.slices[i].subSlices)this.slices[i].subSlices.splice(0,this.slices[i].subSlices.length);ops.push(i);}var originalSlices=this.slices;ops.sort(function(ix,iy){var x=originalSlices[ix];var y=originalSlices[iy];if(x.start!=y.start)return x.start-y.start;return ix-iy;});var slices=new Array(this.slices.length);for(var i=0;i<ops.length;i++){slices[i]=originalSlices[ops[i]];}var rootSlice=slices[0];this.topLevelSlices=[];this.topLevelSlices.push(rootSlice);rootSlice.isTopLevel=true;for(var i=1;i<slices.length;i++){var slice=slices[i];while(rootSlice!==undefined&&!addSliceIfBounds(rootSlice,slice)){rootSlice=rootSlice.parentSlice;}if(rootSlice===undefined){this.topLevelSlices.push(slice);slice.isTopLevel=true;}rootSlice=slice;}this.slices=slices;},addCpuTimeToSubslices_:function(timeSlices){var SCHEDULING_STATE=tr.model.SCHEDULING_STATE;var sliceIdx=0;timeSlices.forEach(function(timeSlice){if(timeSlice.schedulingState==SCHEDULING_STATE.RUNNING){while(sliceIdx<this.topLevelSlices.length){if(this.addCpuTimeToSubslice_(this.topLevelSlices[sliceIdx],timeSlice)){sliceIdx++;}else{break;}}}},this);},addCpuTimeToSubslice_:function(slice,timeSlice){if(slice.start>timeSlice.end||slice.end<timeSlice.start)return slice.end<=timeSlice.end;var duration=timeSlice.duration;if(slice.start>timeSlice.start)duration-=slice.start-timeSlice.start;if(timeSlice.end>slice.end)duration-=timeSlice.end-slice.end;if(slice.cpuDuration){slice.cpuDuration+=duration;}else{slice.cpuDuration=duration;}for(var i=0;i<slice.subSlices.length;i++){this.addCpuTimeToSubslice_(slice.subSlices[i],timeSlice);}return slice.end<=timeSlice.end;}};SliceGroup.merge=function(groupA,groupB){if(groupA.openPartialSlices_.length>0)throw new Error('groupA has open partial slices');if(groupB.openPartialSlices_.length>0)throw new Error('groupB has open partial slices');if(groupA.parentContainer!=groupB.parentContainer)throw new Error('Different parent threads. Cannot merge');if(groupA.sliceConstructor!=groupB.sliceConstructor)throw new Error('Different slice constructors. Cannot merge');var result=new SliceGroup(groupA.parentContainer,groupA.sliceConstructor,groupA.name_);var slicesA=groupA.slices;var slicesB=groupB.slices;var idxA=0;var idxB=0;var openA=[];var openB=[];var splitOpenSlices=function(when){for(var i=0;i<openB.length;i++){var oldSlice=openB[i];var oldEnd=oldSlice.end;if(when<oldSlice.start||oldEnd<when){throw new Error('slice should not be split');}var newSlice=result.copySlice(oldSlice);newSlice.start=when;newSlice.duration=oldEnd-when;if(newSlice.title.indexOf(' (cont.)')==-1)newSlice.title+=' (cont.)';oldSlice.duration=when-oldSlice.start;openB[i]=newSlice;result.pushSlice(newSlice);}};var closeOpenSlices=function(upTo){while(openA.length>0||openB.length>0){var nextA=openA[openA.length-1];var nextB=openB[openB.length-1];var endA=nextA&&nextA.end;var endB=nextB&&nextB.end;if((endA===undefined||endA>upTo)&&(endB===undefined||endB>upTo)){return;}if(endB===undefined||endA<endB){splitOpenSlices(endA);openA.pop();}else{openB.pop();}}};while(idxA<slicesA.length||idxB<slicesB.length){var sA=slicesA[idxA];var sB=slicesB[idxB];var nextSlice,isFromB;if(sA===undefined||sB!==undefined&&sA.start>sB.start){nextSlice=result.copySlice(sB);isFromB=true;idxB++;}else{nextSlice=result.copySlice(sA);isFromB=false;idxA++;}closeOpenSlices(nextSlice.start);result.pushSlice(nextSlice);if(isFromB){openB.push(nextSlice);}else{splitOpenSlices(nextSlice.start);openA.push(nextSlice);}}closeOpenSlices();return result;};return{SliceGroup:SliceGroup};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/stack_frame.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/stack_frame.js

Statements: 12.24% (6 / 49)      Branches: 0% (0 / 22)      Functions: 7.69% (1 / 13)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){function StackFrame(parentFrame,id,title,colorId,opt_sourceInfo){if(id===undefined)throw new Error('id must be given');this.parentFrame_=parentFrame;this.id=id;this.title_=title;this.colorId=colorId;this.children=[];this.sourceInfo_=opt_sourceInfo;if(this.parentFrame_)this.parentFrame_.addChild(this);}StackFrame.prototype={get parentFrame(){return this.parentFrame_;},get title(){if(this.sourceInfo_){var src=this.sourceInfo_.toString();return this.title_+(src===''?'':' '+src);}return this.title_;},get domain(){var result='unknown';if(this.sourceInfo_&&this.sourceInfo_.domain)result=this.sourceInfo_.domain;if(result==='unknown'&&this.parentFrame)result=this.parentFrame.domain;return result;},get sourceInfo(){return this.sourceInfo_;},set parentFrame(parentFrame){if(this.parentFrame_)Polymer.dom(this.parentFrame_).removeChild(this);this.parentFrame_=parentFrame;if(this.parentFrame_)this.parentFrame_.addChild(this);},addChild:function(child){this.children.push(child);},removeChild:function(child){var i=this.children.indexOf(child.id);if(i==-1)throw new Error('omg');this.children.splice(i,1);},removeAllChildren:function(){for(var i=0;i<this.children.length;i++)this.children[i].parentFrame_=undefined;this.children.splice(0,this.children.length);},get stackTrace(){var stack=[];var cur=this;while(cur){stack.push(cur);cur=cur.parentFrame;}return stack;},getUserFriendlyStackTrace:function(){return this.stackTrace.map(function(x){return x.title;});}};return{StackFrame:StackFrame};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/thread.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/thread.js

Statements: 12.34% (19 / 154)      Branches: 0% (0 / 66)      Functions: 3.03% (1 / 33)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/guid.js");require("../base/range.js");require("./async_slice_group.js");require("./event_container.js");require("./slice_group.js");require("./thread_slice.js");'use strict';global.tr.exportTo('tr.model',function(){var AsyncSlice=tr.model.AsyncSlice;var AsyncSliceGroup=tr.model.AsyncSliceGroup;var SliceGroup=tr.model.SliceGroup;var ThreadSlice=tr.model.ThreadSlice;var ThreadTimeSlice=tr.model.ThreadTimeSlice;function Thread(parent,tid){if(!parent)throw new Error('Parent must be provided.');tr.model.EventContainer.call(this);this.parent=parent;this.sortIndex=0;this.tid=tid;this.name=undefined;this.samples_=undefined;var that=this;this.sliceGroup=new SliceGroup(this,ThreadSlice,'slices');this.timeSlices=undefined;this.kernelSliceGroup=new SliceGroup(this,ThreadSlice,'kernel-slices');this.asyncSliceGroup=new AsyncSliceGroup(this,'async-slices');}Thread.prototype={__proto__:tr.model.EventContainer.prototype,get model(){return this.parent.model;},get stableId(){return this.parent.stableId+'.'+this.tid;},compareTo:function(that){return Thread.compare(this,that);},childEventContainers:function*(){if(this.sliceGroup.length)yield this.sliceGroup;if(this.kernelSliceGroup.length)yield this.kernelSliceGroup;if(this.asyncSliceGroup.length)yield this.asyncSliceGroup;},childEvents:function*(){if(this.timeSlices)yield*this.timeSlices;},iterateAllPersistableObjects:function(cb){cb(this);if(this.sliceGroup.length)cb(this.sliceGroup);this.asyncSliceGroup.viewSubGroups.forEach(cb);},shiftTimestampsForward:function(amount){this.sliceGroup.shiftTimestampsForward(amount);if(this.timeSlices){for(var i=0;i<this.timeSlices.length;i++){var slice=this.timeSlices[i];slice.start+=amount;}}this.kernelSliceGroup.shiftTimestampsForward(amount);this.asyncSliceGroup.shiftTimestampsForward(amount);},get isEmpty(){if(this.sliceGroup.length)return false;if(this.sliceGroup.openSliceCount)return false;if(this.timeSlices&&this.timeSlices.length)return false;if(this.kernelSliceGroup.length)return false;if(this.asyncSliceGroup.length)return false;if(this.samples_.length)return false;return true;},updateBounds:function(){this.bounds.reset();this.sliceGroup.updateBounds();this.bounds.addRange(this.sliceGroup.bounds);this.kernelSliceGroup.updateBounds();this.bounds.addRange(this.kernelSliceGroup.bounds);this.asyncSliceGroup.updateBounds();this.bounds.addRange(this.asyncSliceGroup.bounds);if(this.timeSlices&&this.timeSlices.length){this.bounds.addValue(this.timeSlices[0].start);this.bounds.addValue(this.timeSlices[this.timeSlices.length-1].end);}if(this.samples_&&this.samples_.length){this.bounds.addValue(this.samples_[0].start);this.bounds.addValue(this.samples_[this.samples_.length-1].end);}},addCategoriesToDict:function(categoriesDict){for(var i=0;i<this.sliceGroup.length;i++)categoriesDict[this.sliceGroup.slices[i].category]=true;for(var i=0;i<this.kernelSliceGroup.length;i++)categoriesDict[this.kernelSliceGroup.slices[i].category]=true;for(var i=0;i<this.asyncSliceGroup.length;i++)categoriesDict[this.asyncSliceGroup.slices[i].category]=true;if(this.samples_){for(var i=0;i<this.samples_.length;i++)categoriesDict[this.samples_[i].category]=true;}},autoCloseOpenSlices:function(){this.sliceGroup.autoCloseOpenSlices();this.kernelSliceGroup.autoCloseOpenSlices();},mergeKernelWithUserland:function(){if(this.kernelSliceGroup.length>0){var newSlices=SliceGroup.merge(this.sliceGroup,this.kernelSliceGroup);this.sliceGroup.slices=newSlices.slices;this.kernelSliceGroup=new SliceGroup(this);this.updateBounds();}},createSubSlices:function(){this.sliceGroup.createSubSlices();this.samples_=this.parent.model.samples.filter(function(sample){return sample.thread==this;},this);},get userFriendlyName(){return this.name||this.tid;},get userFriendlyDetails(){return'tid: '+this.tid+(this.name?', name: '+this.name:'');},getSettingsKey:function(){if(!this.name)return undefined;var parentKey=this.parent.getSettingsKey();if(!parentKey)return undefined;return parentKey+'.'+this.name;},getProcess:function(){return this.parent;},indexOfTimeSlice:function(timeSlice){var i=tr.b.findLowIndexInSortedArray(this.timeSlices,function(slice){return slice.start;},timeSlice.start);if(this.timeSlices[i]!==timeSlice)return undefined;return i;},getCpuStatsForRange:function(range){var stats={};stats.total=0;if(!this.timeSlices)return stats;function addStatsForSlice(threadTimeSlice){var freqRange=tr.b.Range.fromExplicitRange(threadTimeSlice.start,threadTimeSlice.end);var intersection=freqRange.findIntersection(range);if(threadTimeSlice.schedulingState==tr.model.SCHEDULING_STATE.RUNNING){var cpu=threadTimeSlice.cpuOnWhichThreadWasRunning;if(!(cpu.cpuNumber in stats))stats[cpu.cpuNumber]=0;stats[cpu.cpuNumber]+=intersection.duration;stats.total+=intersection.duration;}}tr.b.iterateOverIntersectingIntervals(this.timeSlices,function(x){return x.start;},function(x){return x.end;},range.min,range.max,addStatsForSlice);return stats;},getSchedulingStatsForRange:function(start,end){var stats={};if(!this.timeSlices)return stats;function addStatsForSlice(threadTimeSlice){var overlapStart=Math.max(threadTimeSlice.start,start);var overlapEnd=Math.min(threadTimeSlice.end,end);var schedulingState=threadTimeSlice.schedulingState;if(!(schedulingState in stats))stats[schedulingState]=0;stats[schedulingState]+=overlapEnd-overlapStart;}tr.b.iterateOverIntersectingIntervals(this.timeSlices,function(x){return x.start;},function(x){return x.end;},start,end,addStatsForSlice);return stats;},get samples(){return this.samples_;}};Thread.compare=function(x,y){var tmp=x.parent.compareTo(y.parent);if(tmp)return tmp;tmp=x.sortIndex-y.sortIndex;if(tmp)return tmp;tmp=tr.b.comparePossiblyUndefinedValues(x.name,y.name,function(x,y){return x.localeCompare(y);});if(tmp)return tmp;return x.tid-y.tid;};return{Thread:Thread};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/thread_slice.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/thread_slice.js

Statements: 47.06% (8 / 17)      Branches: 0% (0 / 8)      Functions: 25% (1 / 4)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./slice.js");'use strict';global.tr.exportTo('tr.model',function(){var Slice=tr.model.Slice;function ThreadSlice(cat,title,colorId,start,args,opt_duration,opt_cpuStart,opt_cpuDuration,opt_argsStripped,opt_bindId){Slice.call(this,cat,title,colorId,start,args,opt_duration,opt_cpuStart,opt_cpuDuration,opt_argsStripped,opt_bindId);this.subSlices=[];}ThreadSlice.prototype={__proto__:Slice.prototype,get overlappingSamples(){var samples=new tr.model.EventSet();if(!this.parentContainer||!this.parentContainer.samples)return samples;this.parentContainer.samples.forEach(function(sample){if(this.start<=sample.start&&sample.start<=this.end)samples.push(sample);},this);return samples;}};tr.model.EventRegistry.register(ThreadSlice,{name:'slice',pluralName:'slices'});return{ThreadSlice:ThreadSlice};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/thread_time_slice.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/thread_time_slice.js

Statements: 18.18% (10 / 55)      Branches: 0% (0 / 34)      Functions: 16.67% (1 / 6)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/range.js");require("./slice.js");'use strict';global.tr.exportTo('tr.model',function(){var Slice=tr.model.Slice;var SCHEDULING_STATE={DEBUG:'Debug',EXIT_DEAD:'Exit Dead',RUNNABLE:'Runnable',RUNNING:'Running',SLEEPING:'Sleeping',STOPPED:'Stopped',TASK_DEAD:'Task Dead',UNINTR_SLEEP:'Uninterruptible Sleep',UNINTR_SLEEP_WAKE_KILL:'Uninterruptible Sleep | WakeKill',UNINTR_SLEEP_WAKING:'Uninterruptible Sleep | Waking',UNINTR_SLEEP_IO:'Uninterruptible Sleep - Block I/O',UNINTR_SLEEP_WAKE_KILL_IO:'Uninterruptible Sleep | WakeKill - Block I/O',UNINTR_SLEEP_WAKING_IO:'Uninterruptible Sleep | Waking - Block I/O',UNKNOWN:'UNKNOWN',WAKE_KILL:'Wakekill',WAKING:'Waking',ZOMBIE:'Zombie'};function ThreadTimeSlice(thread,schedulingState,cat,start,args,opt_duration){Slice.call(this,cat,schedulingState,this.getColorForState_(schedulingState),start,args,opt_duration);this.thread=thread;this.schedulingState=schedulingState;this.cpuOnWhichThreadWasRunning=undefined;}ThreadTimeSlice.prototype={__proto__:Slice.prototype,getColorForState_:function(state){var getColorIdForReservedName=tr.b.ColorScheme.getColorIdForReservedName;switch(state){case SCHEDULING_STATE.RUNNABLE:return getColorIdForReservedName('thread_state_runnable');case SCHEDULING_STATE.RUNNING:return getColorIdForReservedName('thread_state_running');case SCHEDULING_STATE.SLEEPING:return getColorIdForReservedName('thread_state_sleeping');case SCHEDULING_STATE.DEBUG:case SCHEDULING_STATE.EXIT_DEAD:case SCHEDULING_STATE.STOPPED:case SCHEDULING_STATE.TASK_DEAD:case SCHEDULING_STATE.UNINTR_SLEEP:case SCHEDULING_STATE.UNINTR_SLEEP_WAKE_KILL:case SCHEDULING_STATE.UNINTR_SLEEP_WAKING:case SCHEDULING_STATE.UNKNOWN:case SCHEDULING_STATE.WAKE_KILL:case SCHEDULING_STATE.WAKING:case SCHEDULING_STATE.ZOMBIE:return getColorIdForReservedName('thread_state_uninterruptible');case SCHEDULING_STATE.UNINTR_SLEEP_IO:case SCHEDULING_STATE.UNINTR_SLEEP_WAKE_KILL_IO:case SCHEDULING_STATE.UNINTR_SLEEP_WAKING_IO:return getColorIdForReservedName('thread_state_iowait');default:return getColorIdForReservedName('thread_state_unknown');}},get analysisTypeName(){return'tr.ui.analysis.ThreadTimeSlice';},getAssociatedCpuSlice:function(){if(!this.cpuOnWhichThreadWasRunning)return undefined;var cpuSlices=this.cpuOnWhichThreadWasRunning.slices;for(var i=0;i<cpuSlices.length;i++){var cpuSlice=cpuSlices[i];if(cpuSlice.start!==this.start)continue;if(cpuSlice.duration!==this.duration)continue;return cpuSlice;}return undefined;},getCpuSliceThatTookCpu:function(){if(this.cpuOnWhichThreadWasRunning)return undefined;var curIndex=this.thread.indexOfTimeSlice(this);var cpuSliceWhenLastRunning;while(curIndex>=0){var curSlice=this.thread.timeSlices[curIndex];if(!curSlice.cpuOnWhichThreadWasRunning){curIndex--;continue;}cpuSliceWhenLastRunning=curSlice.getAssociatedCpuSlice();break;}if(!cpuSliceWhenLastRunning)return undefined;var cpu=cpuSliceWhenLastRunning.cpu;var indexOfSliceOnCpuWhenLastRunning=cpu.indexOf(cpuSliceWhenLastRunning);var nextRunningSlice=cpu.slices[indexOfSliceOnCpuWhenLastRunning+1];if(!nextRunningSlice)return undefined;if(Math.abs(nextRunningSlice.start-cpuSliceWhenLastRunning.end)<0.00001)return nextRunningSlice;return undefined;}};tr.model.EventRegistry.register(ThreadTimeSlice,{name:'threadTimeSlice',pluralName:'threadTimeSlices'});return{ThreadTimeSlice:ThreadTimeSlice,SCHEDULING_STATE:SCHEDULING_STATE};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/time_to_object_instance_map.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/time_to_object_instance_map.js

Statements: 7.87% (7 / 89)      Branches: 0% (0 / 46)      Functions: 8.33% (1 / 12)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/range.js");require("../base/sorted_array_utils.js");'use strict';global.tr.exportTo('tr.model',function(){function TimeToObjectInstanceMap(createObjectInstanceFunction,parent,scopedId){this.createObjectInstanceFunction_=createObjectInstanceFunction;this.parent=parent;this.scopedId=scopedId;this.instances=[];}TimeToObjectInstanceMap.prototype={idWasCreated:function(category,name,ts){if(this.instances.length==0){this.instances.push(this.createObjectInstanceFunction_(this.parent,this.scopedId,category,name,ts));this.instances[0].creationTsWasExplicit=true;return this.instances[0];}var lastInstance=this.instances[this.instances.length-1];if(ts<lastInstance.deletionTs){throw new Error('Mutation of the TimeToObjectInstanceMap must be '+'done in ascending timestamp order.');}lastInstance=this.createObjectInstanceFunction_(this.parent,this.scopedId,category,name,ts);lastInstance.creationTsWasExplicit=true;this.instances.push(lastInstance);return lastInstance;},addSnapshot:function(category,name,ts,args,opt_baseTypeName){if(this.instances.length==0){this.instances.push(this.createObjectInstanceFunction_(this.parent,this.scopedId,category,name,ts,opt_baseTypeName));}var i=tr.b.findIndexInSortedIntervals(this.instances,function(inst){return inst.creationTs;},function(inst){return inst.deletionTs-inst.creationTs;},ts);var instance;if(i<0){instance=this.instances[0];if(ts>instance.deletionTs||instance.creationTsWasExplicit){throw new Error('At the provided timestamp, no instance was still alive');}if(instance.snapshots.length!=0){throw new Error('Cannot shift creationTs forward, '+'snapshots have been added. First snap was at ts='+instance.snapshots[0].ts+' and creationTs was '+instance.creationTs);}instance.creationTs=ts;}else if(i>=this.instances.length){instance=this.instances[this.instances.length-1];if(ts>=instance.deletionTs){instance=this.createObjectInstanceFunction_(this.parent,this.scopedId,category,name,ts,opt_baseTypeName);this.instances.push(instance);}else{var lastValidIndex;for(var i=this.instances.length-1;i>=0;i--){var tmp=this.instances[i];if(ts>=tmp.deletionTs)break;if(tmp.creationTsWasExplicit==false&&tmp.snapshots.length==0)lastValidIndex=i;}if(lastValidIndex===undefined){throw new Error('Cannot add snapshot. No instance was alive that was mutable.');}instance=this.instances[lastValidIndex];instance.creationTs=ts;}}else{instance=this.instances[i];}return instance.addSnapshot(ts,args,name,opt_baseTypeName);},get lastInstance(){if(this.instances.length==0)return undefined;return this.instances[this.instances.length-1];},idWasDeleted:function(category,name,ts){if(this.instances.length==0){this.instances.push(this.createObjectInstanceFunction_(this.parent,this.scopedId,category,name,ts));}var lastInstance=this.instances[this.instances.length-1];if(ts<lastInstance.creationTs)throw new Error('Cannot delete an id before it was created');if(lastInstance.deletionTs==Number.MAX_VALUE){lastInstance.wasDeleted(ts);return lastInstance;}if(ts<lastInstance.deletionTs)throw new Error('id was already deleted earlier.');lastInstance=this.createObjectInstanceFunction_(this.parent,this.scopedId,category,name,ts);this.instances.push(lastInstance);lastInstance.wasDeleted(ts);return lastInstance;},getInstanceAt:function(ts){var i=tr.b.findIndexInSortedIntervals(this.instances,function(inst){return inst.creationTs;},function(inst){return inst.deletionTs-inst.creationTs;},ts);if(i<0){if(this.instances[0].creationTsWasExplicit)return undefined;return this.instances[0];}else if(i>=this.instances.length){return undefined;}return this.instances[i];},logToConsole:function(){for(var i=0;i<this.instances.length;i++){var instance=this.instances[i];var cEF='';var dEF='';if(instance.creationTsWasExplicit)cEF='(explicitC)';if(instance.deletionTsWasExplicit)dEF='(explicit)';console.log(instance.creationTs,cEF,instance.deletionTs,dEF,instance.category,instance.name,instance.snapshots.length+' snapshots');}}};return{TimeToObjectInstanceMap:TimeToObjectInstanceMap};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/timed_event.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/timed_event.js

Statements: 36.36% (8 / 22)      Branches: 0% (0 / 4)      Functions: 20% (1 / 5)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/guid.js");require("../base/time_display_modes.js");require("./event.js");'use strict';global.tr.exportTo('tr.model',function(){function TimedEvent(start){tr.model.Event.call(this);this.start=start;this.duration=0;this.cpuStart=undefined;this.cpuDuration=undefined;this.contexts=Object.freeze([]);}TimedEvent.prototype={__proto__:tr.model.Event.prototype,get end(){return this.start+this.duration;},addBoundsToRange:function(range){range.addValue(this.start);range.addValue(this.end);},bounds:function(that,opt_precisionUnit){if(opt_precisionUnit===undefined)opt_precisionUnit=tr.b.TimeDisplayModes.ms;var startsBefore=opt_precisionUnit.roundedLess(that.start,this.start);var endsAfter=opt_precisionUnit.roundedLess(this.end,that.end);return!startsBefore&&!endsAfter;}};return{TimedEvent:TimedEvent};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/vm_region.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/vm_region.js

Statements: 15.89% (17 / 107)      Branches: 0% (0 / 58)      Functions: 4.55% (1 / 22)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/base.js");'use strict';global.tr.exportTo('tr.model',function(){function VMRegion(startAddress,sizeInBytes,protectionFlags,mappedFile,byteStats){this.startAddress=startAddress;this.sizeInBytes=sizeInBytes;this.protectionFlags=protectionFlags;this.mappedFile=mappedFile||'';this.byteStats=byteStats||{};};VMRegion.PROTECTION_FLAG_READ=4;VMRegion.PROTECTION_FLAG_WRITE=2;VMRegion.PROTECTION_FLAG_EXECUTE=1;VMRegion.PROTECTION_FLAG_MAYSHARE=128;VMRegion.prototype={get uniqueIdWithinProcess(){return this.mappedFile+'#'+this.startAddress;},get protectionFlagsToString(){if(this.protectionFlags===undefined)return undefined;return(this.protectionFlags&VMRegion.PROTECTION_FLAG_READ?'r':'-')+(this.protectionFlags&VMRegion.PROTECTION_FLAG_WRITE?'w':'-')+(this.protectionFlags&VMRegion.PROTECTION_FLAG_EXECUTE?'x':'-')+(this.protectionFlags&VMRegion.PROTECTION_FLAG_MAYSHARE?'s':'p');}};VMRegion.fromDict=function(dict){return new VMRegion(dict.startAddress,dict.sizeInBytes,dict.protectionFlags,dict.mappedFile,dict.byteStats);};function VMRegionClassificationNode(opt_rule){this.rule_=opt_rule||VMRegionClassificationNode.CLASSIFICATION_RULES;this.hasRegions=false;this.sizeInBytes=undefined;this.byteStats={};this.children_=undefined;this.regions_=[];}VMRegionClassificationNode.CLASSIFICATION_RULES={name:'Total',children:[{name:'Android',file:/^\/dev\/ashmem(?!\/libc malloc)/,children:[{name:'Java runtime',file:/^\/dev\/ashmem\/dalvik-/,children:[{name:'Spaces',file:/\/dalvik-(alloc|main|large object|non moving|zygote) space/,children:[{name:'Normal',file:/\/dalvik-(alloc|main)/},{name:'Large',file:/\/dalvik-large object/},{name:'Zygote',file:/\/dalvik-zygote/},{name:'Non-moving',file:/\/dalvik-non moving/}]},{name:'Linear Alloc',file:/\/dalvik-LinearAlloc/},{name:'Indirect Reference Table',file:/\/dalvik-indirect.ref/},{name:'Cache',file:/\/dalvik-jit-code-cache/},{name:'Accounting'}]},{name:'Cursor',file:/\/CursorWindow/},{name:'Ashmem'}]},{name:'Native heap',file:/^((\[heap\])|(\[anon:)|(\/dev\/ashmem\/libc malloc)|(\[discounted tracing overhead\])|$)/},{name:'Stack',file:/^\[stack/},{name:'Files',file:/\.((((jar)|(apk)|(ttf)|(odex)|(oat)|(art))$)|(dex)|(so))/,children:[{name:'so',file:/\.so/},{name:'jar',file:/\.jar$/},{name:'apk',file:/\.apk$/},{name:'ttf',file:/\.ttf$/},{name:'dex',file:/\.((dex)|(odex$))/},{name:'oat',file:/\.oat$/},{name:'art',file:/\.art$/}]},{name:'Devices',file:/(^\/dev\/)|(anon_inode:dmabuf)/,children:[{name:'GPU',file:/\/((nv)|(mali)|(kgsl))/},{name:'DMA',file:/anon_inode:dmabuf/}]}]};VMRegionClassificationNode.OTHER_RULE={name:'Other'};VMRegionClassificationNode.fromRegions=function(regions,opt_rules){var tree=new VMRegionClassificationNode(opt_rules);tree.regions_=regions;for(var i=0;i<regions.length;i++)tree.addStatsFromRegion_(regions[i]);return tree;};VMRegionClassificationNode.prototype={get title(){return this.rule_.name;},get children(){if(this.isLeafNode)return undefined;if(this.children_===undefined)this.buildTree_();return this.children_;},get regions(){if(!this.isLeafNode){return undefined;}return this.regions_;},get allRegionsForTesting(){if(this.regions_!==undefined){if(this.children_!==undefined){throw new Error('Internal error: a VM region classification node '+'cannot have both regions and children');}return this.regions_;}var regions=[];this.children_.forEach(function(childNode){regions=regions.concat(childNode.allRegionsForTesting);});return regions;},get isLeafNode(){var children=this.rule_.children;return children===undefined||children.length===0;},addRegion:function(region){this.addRegionRecursively_(region,true);},someRegion:function(fn,opt_this){if(this.regions_!==undefined){return this.regions_.some(fn,opt_this);}return this.children_.some(function(childNode){return childNode.someRegion(fn,opt_this);});},addRegionRecursively_:function(region,addStatsToThisNode){if(addStatsToThisNode)this.addStatsFromRegion_(region);if(this.regions_!==undefined){if(this.children_!==undefined){throw new Error('Internal error: a VM region classification node '+'cannot have both regions and children');}this.regions_.push(region);return;}function regionRowMatchesChildNide(child){var fileRegExp=child.rule_.file;if(fileRegExp===undefined)return true;return fileRegExp.test(region.mappedFile);}var matchedChild=tr.b.findFirstInArray(this.children_,regionRowMatchesChildNide);if(matchedChild===undefined){if(this.children_.length!==this.rule_.children.length)throw new Error('Internal error');matchedChild=new VMRegionClassificationNode(VMRegionClassificationNode.OTHER_RULE);this.children_.push(matchedChild);}matchedChild.addRegionRecursively_(region,true);},buildTree_:function(){var cachedRegions=this.regions_;this.regions_=undefined;this.buildChildNodesRecursively_();for(var i=0;i<cachedRegions.length;i++){this.addRegionRecursively_(cachedRegions[i],false);}},buildChildNodesRecursively_:function(){if(this.children_!==undefined){throw new Error('Internal error: Classification node already has children');}if(this.regions_!==undefined&&this.regions_.length!==0){throw new Error('Internal error: Classification node should have no regions');}if(this.isLeafNode)return;this.regions_=undefined;this.children_=this.rule_.children.map(function(childRule){var child=new VMRegionClassificationNode(childRule);child.buildChildNodesRecursively_();return child;});},addStatsFromRegion_:function(region){this.hasRegions=true;var regionSizeInBytes=region.sizeInBytes;if(regionSizeInBytes!==undefined)this.sizeInBytes=(this.sizeInBytes||0)+regionSizeInBytes;var thisByteStats=this.byteStats;var regionByteStats=region.byteStats;for(var byteStatName in regionByteStats){var regionByteStatValue=regionByteStats[byteStatName];if(regionByteStatValue===undefined)continue;thisByteStats[byteStatName]=(thisByteStats[byteStatName]||0)+regionByteStatValue;}}};return{VMRegion:VMRegion,VMRegionClassificationNode:VMRegionClassificationNode};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/x_marker_annotation.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/x_marker_annotation.js

Statements: 60% (9 / 15)      Branches: 100% (0 / 0)      Functions: 20% (1 / 5)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./annotation.js");require("../ui/annotations/x_marker_annotation_view.js");'use strict';global.tr.exportTo('tr.model',function(){function XMarkerAnnotation(timestamp){tr.model.Annotation.apply(this,arguments);this.timestamp=timestamp;this.strokeStyle='rgba(0, 0, 255, 0.5)';}XMarkerAnnotation.fromDict=function(dict){return new XMarkerAnnotation(dict.args.timestamp);};XMarkerAnnotation.prototype={__proto__:tr.model.Annotation.prototype,toDict:function(){return{typeName:'xmarker',args:{timestamp:this.timestamp}};},createView_:function(viewport){return new tr.ui.annotations.XMarkerAnnotationView(viewport,this);}};tr.model.Annotation.register(XMarkerAnnotation,{typeName:'xmarker'});return{XMarkerAnnotation:XMarkerAnnotation};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/

Statements: 24% (54 / 225)      Branches: 0% (0 / 80)      Functions: 8.93% (5 / 56)      Lines: 100% (5 / 5)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/
File Statements Branches Functions Lines
chrome_browser_helper.js 16.36% (9 / 55) 0% (0 / 25) 4.76% (1 / 21) 100% (1 / 1)
chrome_gpu_helper.js 50% (8 / 16) 0% (0 / 6) 25% (1 / 4) 100% (1 / 1)
chrome_model_helper.js 30.61% (15 / 49) 0% (0 / 10) 6.67% (1 / 15) 100% (1 / 1)
chrome_process_helper.js 34.29% (12 / 35) 0% (0 / 8) 14.29% (1 / 7) 100% (1 / 1)
chrome_renderer_helper.js 14.29% (10 / 70) 0% (0 / 31) 11.11% (1 / 9) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/chrome_browser_helper.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/chrome_browser_helper.js

Statements: 16.36% (9 / 55)      Branches: 0% (0 / 25)      Functions: 4.76% (1 / 21)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/iteration_helpers.js");require("./chrome_process_helper.js");'use strict';global.tr.exportTo('tr.model.helpers',function(){function ChromeBrowserHelper(modelHelper,process){tr.model.helpers.ChromeProcessHelper.call(this,modelHelper,process);this.mainThread_=process.findAtMostOneThreadNamed('CrBrowserMain');if(!process.name)process.name=ChromeBrowserHelper.PROCESS_NAME;}ChromeBrowserHelper.PROCESS_NAME='Browser';ChromeBrowserHelper.isBrowserProcess=function(process){return!!process.findAtMostOneThreadNamed('CrBrowserMain');};ChromeBrowserHelper.prototype={__proto__:tr.model.helpers.ChromeProcessHelper.prototype,get browserName(){var hasInProcessRendererThread=this.process.findAllThreadsNamed('Chrome_InProcRendererThread').length>0;return hasInProcessRendererThread?'webview':'chrome';},get rendererHelpers(){return this.modelHelper.rendererHelpers;},getLoadingEventsInRange:function(rangeOfInterest){return this.getAllAsyncSlicesMatching(function(slice){return slice.title.indexOf('WebContentsImpl Loading')===0&&rangeOfInterest.intersectsExplicitRangeInclusive(slice.start,slice.end);});},getCommitProvisionalLoadEventsInRange:function(rangeOfInterest){return this.getAllAsyncSlicesMatching(function(slice){return slice.title==='RenderFrameImpl::didCommitProvisionalLoad'&&rangeOfInterest.intersectsExplicitRangeInclusive(slice.start,slice.end);});},get hasLatencyEvents(){var hasLatency=false;for(var thread of this.modelHelper.model.getAllThreads())for(var event of thread.getDescendantEvents()){if(!event.isTopLevel)continue;if(!(event instanceof tr.e.cc.InputLatencyAsyncSlice))continue;hasLatency=true;}return hasLatency;},getLatencyEventsInRange:function(rangeOfInterest){return this.getAllAsyncSlicesMatching(function(slice){return slice.title.indexOf('InputLatency')===0&&rangeOfInterest.intersectsExplicitRangeInclusive(slice.start,slice.end);});},getAllAsyncSlicesMatching:function(pred,opt_this){var events=[];this.iterAllThreads(function(thread){for(var slice of thread.getDescendantEvents())if(pred.call(opt_this,slice))events.push(slice);});return events;},getAllNetworkEventsInRange:function(rangeOfInterest){var networkEvents=[];this.modelHelper.model.getAllThreads().forEach(function(thread){thread.asyncSliceGroup.slices.forEach(function(slice){var match=false;if(slice.category=='net'||slice.category=='disabled-by-default-netlog'||slice.category=='netlog'){match=true;}if(!match)return;if(rangeOfInterest.intersectsExplicitRangeInclusive(slice.start,slice.end))networkEvents.push(slice);});});return networkEvents;},iterAllThreads:function(func,opt_this){tr.b.iterItems(this.process.threads,function(tid,thread){func.call(opt_this,thread);});tr.b.iterItems(this.rendererHelpers,function(pid,rendererHelper){var rendererProcess=rendererHelper.process;tr.b.iterItems(rendererProcess.threads,function(tid,thread){func.call(opt_this,thread);});},this);}};return{ChromeBrowserHelper:ChromeBrowserHelper};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/chrome_gpu_helper.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/chrome_gpu_helper.js

Statements: 50% (8 / 16)      Branches: 0% (0 / 6)      Functions: 25% (1 / 4)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./chrome_process_helper.js");'use strict';global.tr.exportTo('tr.model.helpers',function(){function ChromeGpuHelper(modelHelper,process){tr.model.helpers.ChromeProcessHelper.call(this,modelHelper,process);this.mainThread_=process.findAtMostOneThreadNamed('CrGpuMain');if(!process.name)process.name=ChromeGpuHelper.PROCESS_NAME;};ChromeGpuHelper.PROCESS_NAME='GPU Process';ChromeGpuHelper.isGpuProcess=function(process){if(process.findAtMostOneThreadNamed('CrBrowserMain')||process.findAtMostOneThreadNamed('CrRendererMain'))return false;return process.findAtMostOneThreadNamed('CrGpuMain');};ChromeGpuHelper.prototype={__proto__:tr.model.helpers.ChromeProcessHelper.prototype,get mainThread(){return this.mainThread_;}};return{ChromeGpuHelper:ChromeGpuHelper};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/chrome_model_helper.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/chrome_model_helper.js

Statements: 30.61% (15 / 49)      Branches: 0% (0 / 10)      Functions: 6.67% (1 / 15)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/guid.js");require("../../base/iteration_helpers.js");require("./chrome_browser_helper.js");require("./chrome_gpu_helper.js");require("./chrome_renderer_helper.js");'use strict';global.tr.exportTo('tr.model.helpers',function(){function findChromeBrowserProcesses(model){return model.getAllProcesses(tr.model.helpers.ChromeBrowserHelper.isBrowserProcess);}function findChromeRenderProcesses(model){return model.getAllProcesses(tr.model.helpers.ChromeRendererHelper.isRenderProcess);}function findChromeGpuProcess(model){var gpuProcesses=model.getAllProcesses(tr.model.helpers.ChromeGpuHelper.isGpuProcess);if(gpuProcesses.length!==1)return undefined;return gpuProcesses[0];}function ChromeModelHelper(model){this.model_=model;var browserProcesses=findChromeBrowserProcesses(model);this.browserHelpers_=browserProcesses.map(p=>new tr.model.helpers.ChromeBrowserHelper(this,p));var gpuProcess=findChromeGpuProcess(model);if(gpuProcess){this.gpuHelper_=new tr.model.helpers.ChromeGpuHelper(this,gpuProcess);}else{this.gpuHelper_=undefined;}var rendererProcesses_=findChromeRenderProcesses(model);this.rendererHelpers_={};rendererProcesses_.forEach(function(renderProcess){var rendererHelper=new tr.model.helpers.ChromeRendererHelper(this,renderProcess);this.rendererHelpers_[rendererHelper.pid]=rendererHelper;},this);}ChromeModelHelper.guid=tr.b.GUID.allocateSimple();ChromeModelHelper.supportsModel=function(model){if(findChromeBrowserProcesses(model).length)return true;if(findChromeRenderProcesses(model).length)return true;return false;};ChromeModelHelper.prototype={get pid(){throw new Error('woah');},get process(){throw new Error('woah');},get model(){return this.model_;},get browserProcess(){if(this.browserHelper===undefined)return undefined;return this.browserHelper.process;},get browserHelper(){return this.browserHelpers_[0];},get browserHelpers(){return this.browserHelpers_;},get gpuHelper(){return this.gpuHelper_;},get rendererHelpers(){return this.rendererHelpers_;}};return{ChromeModelHelper:ChromeModelHelper};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/chrome_process_helper.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/chrome_process_helper.js

Statements: 34.29% (12 / 35)      Branches: 0% (0 / 8)      Functions: 14.29% (1 / 7)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/base.js");'use strict';global.tr.exportTo('tr.model.helpers',function(){var MAIN_FRAMETIME_TYPE='main_frametime_type';var IMPL_FRAMETIME_TYPE='impl_frametime_type';var MAIN_RENDERING_STATS='BenchmarkInstrumentation::MainThreadRenderingStats';var IMPL_RENDERING_STATS='BenchmarkInstrumentation::ImplThreadRenderingStats';function getSlicesIntersectingRange(rangeOfInterest,slices){var slicesInFilterRange=[];for(var i=0;i<slices.length;i++){var slice=slices[i];if(rangeOfInterest.intersectsExplicitRangeInclusive(slice.start,slice.end))slicesInFilterRange.push(slice);}return slicesInFilterRange;}function ChromeProcessHelper(modelHelper,process){this.modelHelper=modelHelper;this.process=process;}ChromeProcessHelper.prototype={get pid(){return this.process.pid;},getFrameEventsInRange:function(frametimeType,range){var titleToGet=frametimeType===MAIN_FRAMETIME_TYPE?MAIN_RENDERING_STATS:IMPL_RENDERING_STATS;var frameEvents=[];for(var event of this.process.getDescendantEvents())if(event.title===titleToGet)if(range.intersectsExplicitRangeInclusive(event.start,event.end))frameEvents.push(event);frameEvents.sort(function(a,b){return a.start-b.start;});return frameEvents;}};function getFrametimeDataFromEvents(frameEvents){var frametimeData=[];for(var i=1;i<frameEvents.length;i++){var diff=frameEvents[i].start-frameEvents[i-1].start;frametimeData.push({'x':frameEvents[i].start,'frametime':diff});}return frametimeData;}return{ChromeProcessHelper:ChromeProcessHelper,MAIN_FRAMETIME_TYPE:MAIN_FRAMETIME_TYPE,IMPL_FRAMETIME_TYPE:IMPL_FRAMETIME_TYPE,MAIN_RENDERING_STATS:MAIN_RENDERING_STATS,IMPL_RENDERING_STATS:IMPL_RENDERING_STATS,getSlicesIntersectingRange:getSlicesIntersectingRange,getFrametimeDataFromEvents:getFrametimeDataFromEvents};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/chrome_renderer_helper.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/helpers/chrome_renderer_helper.js

Statements: 14.29% (10 / 70)      Branches: 0% (0 / 31)      Functions: 11.11% (1 / 9)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/range.js");require("../../extras/chrome/chrome_user_friendly_category_driver.js");require("./chrome_process_helper.js");'use strict';global.tr.exportTo('tr.model.helpers',function(){function ChromeRendererHelper(modelHelper,process){tr.model.helpers.ChromeProcessHelper.call(this,modelHelper,process);this.mainThread_=process.findAtMostOneThreadNamed('CrRendererMain');this.compositorThread_=process.findAtMostOneThreadNamed('Compositor');this.rasterWorkerThreads_=process.findAllThreadsMatching(function(t){if(t.name===undefined)return false;if(t.name.indexOf('CompositorTileWorker')===0)return true;if(t.name.indexOf('CompositorRasterWorker')===0)return true;return false;});this.isChromeTracingUI_=process.labels!==undefined&&process.labels.length===1&&process.labels[0]==='chrome://tracing';if(!process.name)process.name=ChromeRendererHelper.PROCESS_NAME;}ChromeRendererHelper.PROCESS_NAME='Renderer';ChromeRendererHelper.isRenderProcess=function(process){if(process.findAtMostOneThreadNamed('CrRendererMain'))return true;if(process.findAtMostOneThreadNamed('Compositor'))return true;return false;};ChromeRendererHelper.prototype={__proto__:tr.model.helpers.ChromeProcessHelper.prototype,get mainThread(){return this.mainThread_;},get compositorThread(){return this.compositorThread_;},get rasterWorkerThreads(){return this.rasterWorkerThreads_;},get isChromeTracingUI(){return this.isChromeTracingUI_;},generateTimeBreakdownTree:function(start,end){if(this.mainThread===null)return;var breakdownMap={};var range=tr.b.Range.fromExplicitRange(start,end);for(var title of tr.e.chrome.ChromeUserFriendlyCategoryDriver.ALL_TITLES){breakdownMap[title]={total:0,events:{}};}breakdownMap['idle']={total:0,events:{}};var totalIdleTime=end-start;for(var event of this.mainThread.getDescendantEvents()){if(!range.intersectsExplicitRangeExclusive(event.start,event.end))continue;if(event.selfTime===undefined)continue;var title=tr.e.chrome.ChromeUserFriendlyCategoryDriver.fromEvent(event);var wallTimeIntersectionRatio=0;if(event.duration>0){wallTimeIntersectionRatio=range.findExplicitIntersectionDuration(event.start,event.end)/event.duration;}var v8Runtime=event.args['runtime-call-stat'];if(v8Runtime!==undefined){try{var v8RuntimeObject=JSON.parse(v8Runtime);for(var runtimeCall in v8RuntimeObject){if(v8RuntimeObject[runtimeCall].length==2){if(breakdownMap['v8_runtime'].events[runtimeCall]===undefined){breakdownMap['v8_runtime'].events[runtimeCall]=0;}var runtimeTime=v8RuntimeObject[runtimeCall][1]*wallTimeIntersectionRatio/1000;breakdownMap['v8_runtime'].total+=runtimeTime;breakdownMap['v8_runtime'].events[runtimeCall]+=runtimeTime;}}}catch(e){console.warn(e);}}var approximatedSelfTimeContribution=event.selfTime*wallTimeIntersectionRatio;breakdownMap[title].total+=approximatedSelfTimeContribution;if(breakdownMap[title].events[event.title]===undefined)breakdownMap[title].events[event.title]=0;breakdownMap[title].events[event.title]+=approximatedSelfTimeContribution;totalIdleTime-=approximatedSelfTimeContribution;}breakdownMap['idle'].total=totalIdleTime;return breakdownMap;}};return{ChromeRendererHelper:ChromeRendererHelper};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/source_info/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/source_info/

Statements: 30.77% (12 / 39)      Branches: 0% (0 / 16)      Functions: 15.38% (2 / 13)      Lines: 100% (2 / 2)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/source_info/
File Statements Branches Functions Lines
js_source_info.js 40% (6 / 15) 0% (0 / 2) 16.67% (1 / 6) 100% (1 / 1)
source_info.js 25% (6 / 24) 0% (0 / 14) 14.29% (1 / 7) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/source_info/js_source_info.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/source_info/js_source_info.js

Statements: 40% (6 / 15)      Branches: 0% (0 / 2)      Functions: 16.67% (1 / 6)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./source_info.js");'use strict';global.tr.exportTo('tr.model.source_info',function(){function JSSourceInfo(file,line,column,isNative,scriptId,state){tr.model.source_info.SourceInfo.call(this,file,line,column);this.isNative_=isNative;this.scriptId_=scriptId;this.state_=state;}JSSourceInfo.prototype={__proto__:tr.model.source_info.SourceInfo.prototype,get state(){return this.state_;},get isNative(){return this.isNative_;},get scriptId(){return this.scriptId_;},toString:function(){var str=this.isNative_?'[native v8] ':'';return str+tr.model.source_info.SourceInfo.prototype.toString.call(this);}};return{JSSourceInfo:JSSourceInfo,JSSourceState:{COMPILED:'compiled',OPTIMIZABLE:'optimizable',OPTIMIZED:'optimized',UNKNOWN:'unknown'}};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/source_info/source_info.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/source_info/source_info.js

Statements: 25% (6 / 24)      Branches: 0% (0 / 14)      Functions: 14.29% (1 / 7)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/base.js");'use strict';global.tr.exportTo('tr.model.source_info',function(){function SourceInfo(file,opt_line,opt_column){this.file_=file;this.line_=opt_line||-1;this.column_=opt_column||-1;}SourceInfo.prototype={get file(){return this.file_;},get line(){return this.line_;},get column(){return this.column_;},get domain(){if(!this.file_)return undefined;var domain=this.file_.match(/(.*:\/\/[^:\/]*)/i);return domain?domain[1]:undefined;},toString:function(){var str='';if(this.file_)str+=this.file_;if(this.line_>0)str+=':'+this.line_;if(this.column_>0)str+=':'+this.column_;return str;}};return{SourceInfo:SourceInfo};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/

Statements: 45.77% (65 / 142)      Branches: 7.14% (2 / 28)      Functions: 20% (8 / 40)      Lines: 100% (7 / 7)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/
File Statements Branches Functions Lines
animation_expectation.js 43.75% (7 / 16) 0% (0 / 4) 25% (1 / 4) 100% (1 / 1)
idle_expectation.js 77.78% (7 / 9) 100% (0 / 0) 50% (1 / 2) 100% (1 / 1)
load_expectation.js 57.89% (11 / 19) 0% (0 / 2) 50% (1 / 2) 100% (1 / 1)
response_expectation.js 77.78% (7 / 9) 0% (0 / 2) 50% (1 / 2) 100% (1 / 1)
startup_expectation.js 87.5% (7 / 8) 100% (0 / 0) 50% (1 / 2) 100% (1 / 1)
user_expectation.js 31.75% (20 / 63) 10% (2 / 20) 12.5% (2 / 16) 100% (1 / 1)
user_model.js 33.33% (6 / 18) 100% (0 / 0) 8.33% (1 / 12) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/animation_expectation.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/animation_expectation.js

Statements: 43.75% (7 / 16)      Branches: 0% (0 / 4)      Functions: 25% (1 / 4)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./user_expectation.js");'use strict';global.tr.exportTo('tr.model.um',function(){function AnimationExpectation(parentModel,initiatorTitle,start,duration){tr.model.um.UserExpectation.call(this,parentModel,initiatorTitle,start,duration);this.frameEvents_=undefined;}AnimationExpectation.prototype={__proto__:tr.model.um.UserExpectation.prototype,constructor:AnimationExpectation,get frameEvents(){if(this.frameEvents_)return this.frameEvents_;this.frameEvents_=new tr.model.EventSet();this.associatedEvents.forEach(function(event){if(event.title===tr.model.helpers.IMPL_RENDERING_STATS)this.frameEvents_.push(event);},this);return this.frameEvents_;}};tr.model.um.UserExpectation.subTypes.register(AnimationExpectation,{stageTitle:'Animation',colorId:tr.b.ColorScheme.getColorIdForReservedName('rail_animation')});return{AnimationExpectation:AnimationExpectation};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/idle_expectation.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/idle_expectation.js

Statements: 77.78% (7 / 9)      Branches: 100% (0 / 0)      Functions: 50% (1 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./user_expectation.js");'use strict';global.tr.exportTo('tr.model.um',function(){function IdleExpectation(parentModel,start,duration){var initiatorTitle='';tr.model.um.UserExpectation.call(this,parentModel,initiatorTitle,start,duration);}IdleExpectation.prototype={__proto__:tr.model.um.UserExpectation.prototype,constructor:IdleExpectation};tr.model.um.UserExpectation.subTypes.register(IdleExpectation,{stageTitle:'Idle',colorId:tr.b.ColorScheme.getColorIdForReservedName('rail_idle')});return{IdleExpectation:IdleExpectation};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/load_expectation.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/load_expectation.js

Statements: 57.89% (11 / 19)      Branches: 0% (0 / 2)      Functions: 50% (1 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 22  
"use strict";require("./user_expectation.js");'use strict';global.tr.exportTo('tr.model.um',function(){var LOAD_SUBTYPE_NAMES={SUCCESSFUL:'Successful',FAILED:'Failed'};var DOES_LOAD_SUBTYPE_NAME_EXIST={};for(var key in LOAD_SUBTYPE_NAMES){DOES_LOAD_SUBTYPE_NAME_EXIST[LOAD_SUBTYPE_NAMES[key]]=true;;}function LoadExpectation(parentModel,initiatorTitle,start,duration){if(!DOES_LOAD_SUBTYPE_NAME_EXIST[initiatorTitle])throw new Error(initiatorTitle+' is not in LOAD_SUBTYPE_NAMES');tr.model.um.UserExpectation.call(this,parentModel,initiatorTitle,start,duration);this.renderProcess=undefined;this.renderMainThread=undefined;this.routingId=undefined;this.parentRoutingId=undefined;this.loadFinishedEvent=undefined;}LoadExpectation.prototype={__proto__:tr.model.um.UserExpectation.prototype,constructor:LoadExpectation};tr.model.um.UserExpectation.subTypes.register(LoadExpectation,{stageTitle:'Load',colorId:tr.b.ColorScheme.getColorIdForReservedName('rail_load')});return{LOAD_SUBTYPE_NAMES:LOAD_SUBTYPE_NAMES,LoadExpectation:LoadExpectation};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/response_expectation.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/response_expectation.js

Statements: 77.78% (7 / 9)      Branches: 0% (0 / 2)      Functions: 50% (1 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./user_expectation.js");'use strict';global.tr.exportTo('tr.model.um',function(){function ResponseExpectation(parentModel,initiatorTitle,start,duration,opt_isAnimationBegin){tr.model.um.UserExpectation.call(this,parentModel,initiatorTitle,start,duration);this.isAnimationBegin=opt_isAnimationBegin||false;}ResponseExpectation.prototype={__proto__:tr.model.um.UserExpectation.prototype,constructor:ResponseExpectation};tr.model.um.UserExpectation.subTypes.register(ResponseExpectation,{stageTitle:'Response',colorId:tr.b.ColorScheme.getColorIdForReservedName('rail_response')});return{ResponseExpectation:ResponseExpectation};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/startup_expectation.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/startup_expectation.js

Statements: 87.5% (7 / 8)      Branches: 100% (0 / 0)      Functions: 50% (1 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./user_expectation.js");'use strict';global.tr.exportTo('tr.model.um',function(){function StartupExpectation(parentModel,start,duration){tr.model.um.UserExpectation.call(this,parentModel,'',start,duration);}StartupExpectation.prototype={__proto__:tr.model.um.UserExpectation.prototype,constructor:StartupExpectation};tr.model.um.UserExpectation.subTypes.register(StartupExpectation,{stageTitle:'Startup',colorId:tr.b.ColorScheme.getColorIdForReservedName('startup')});return{StartupExpectation:StartupExpectation};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/user_expectation.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/user_expectation.js

Statements: 31.75% (20 / 63)      Branches: 10% (2 / 20)      Functions: 12.5% (2 / 16)      Lines: 100% (1 / 1)      Ignored: none     

1 25  
"use strict";require("../../base/range_utils.js");require("../../base/statistics.js");require("../../base/unit.js");require("../compound_event_selection_state.js");require("../event_set.js");require("../timed_event.js");'use strict';global.tr.exportTo('tr.model.um',function(){var CompoundEventSelectionState=tr.model.CompoundEventSelectionState;function UserExpectation(parentModel,initiatorTitle,start,duration){tr.model.TimedEvent.call(this,start);this.associatedEvents=new tr.model.EventSet();this.duration=duration;this.initiatorTitle_=initiatorTitle;this.parentModel=parentModel;this.typeInfo_=undefined;this.sourceEvents=new tr.model.EventSet();}UserExpectation.prototype={__proto__:tr.model.TimedEvent.prototype,computeCompoundEvenSelectionState:function(selection){var cess=CompoundEventSelectionState.NOT_SELECTED;if(selection.contains(this))cess|=CompoundEventSelectionState.EVENT_SELECTED;if(this.associatedEvents.intersectionIsEmpty(selection))return cess;var allContained=this.associatedEvents.every(function(event){return selection.contains(event);});if(allContained)cess|=CompoundEventSelectionState.ALL_ASSOCIATED_EVENTS_SELECTED;else cess|=CompoundEventSelectionState.SOME_ASSOCIATED_EVENTS_SELECTED;return cess;},get associatedSamples(){var samples=new tr.model.EventSet();this.associatedEvents.forEach(function(event){if(event instanceof tr.model.ThreadSlice)samples.addEventSet(event.overlappingSamples);});return samples;},get userFriendlyName(){return this.title+' User Expectation at '+tr.b.Unit.byName.timeStampInMs.format(this.start);},get stableId(){return'UserExpectation.'+this.guid;},get typeInfo(){if(!this.typeInfo_){this.typeInfo_=UserExpectation.subTypes.findTypeInfo(this.constructor);}if(!this.typeInfo_)throw new Error('Unregistered UserExpectation');return this.typeInfo_;},get colorId(){return this.typeInfo.metadata.colorId;},get stageTitle(){return this.typeInfo.metadata.stageTitle;},get initiatorTitle(){return this.initiatorTitle_;},get title(){if(!this.initiatorTitle)return this.stageTitle;return this.initiatorTitle+' '+this.stageTitle;},get totalCpuMs(){var cpuMs=0;this.associatedEvents.forEach(function(event){if(event.cpuSelfTime)cpuMs+=event.cpuSelfTime;});return cpuMs;}};var subTypes={};var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);tr.b.decorateExtensionRegistry(subTypes,options);subTypes.addEventListener('will-register',function(e){var metadata=e.typeInfo.metadata;Iif(metadata.stageTitle===undefined){throw new Error('Registered UserExpectations must provide '+'stageTitle');}Iif(metadata.colorId===undefined){throw new Error('Registered UserExpectations must provide '+'colorId');}});tr.model.EventRegistry.register(UserExpectation,{name:'userExpectation',pluralName:'userExpectations',subTypes:subTypes});return{UserExpectation:UserExpectation};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/user_model.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/model/user_model/user_model.js

Statements: 33.33% (6 / 18)      Branches: 100% (0 / 0)      Functions: 8.33% (1 / 12)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../event_container.js");'use strict';global.tr.exportTo('tr.model.um',function(){function UserModel(parentModel){tr.model.EventContainer.call(this);this.parentModel_=parentModel;this.expectations_=new tr.model.EventSet();}UserModel.prototype={__proto__:tr.model.EventContainer.prototype,get stableId(){return'UserModel';},get parentModel(){return this.parentModel_;},sortExpectations:function(){this.expectations_.sortEvents((x,y)=>x.start-y.start);},get expectations(){return this.expectations_;},shiftTimestampsForward:function(amount){},addCategoriesToDict:function(categoriesDict){},childEvents:function*(){yield*this.expectations;},childEventContainers:function*(){},updateBounds:function(){this.bounds.reset();this.expectations.forEach(function(expectation){expectation.addBoundsToRange(this.bounds);},this);}};return{UserModel:UserModel};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/annotations/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/annotations/

Statements: 30.77% (24 / 78)      Branches: 0% (0 / 10)      Functions: 30.77% (4 / 13)      Lines: 100% (4 / 4)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/annotations/
File Statements Branches Functions Lines
annotation_view.js 85.71% (6 / 7) 100% (0 / 0) 33.33% (1 / 3) 100% (1 / 1)
comment_box_annotation_view.js 15.79% (6 / 38) 0% (0 / 6) 25% (1 / 4) 100% (1 / 1)
rect_annotation_view.js 31.58% (6 / 19) 0% (0 / 4) 33.33% (1 / 3) 100% (1 / 1)
x_marker_annotation_view.js 42.86% (6 / 14) 100% (0 / 0) 33.33% (1 / 3) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/annotations/annotation_view.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/annotations/annotation_view.js

Statements: 85.71% (6 / 7)      Branches: 100% (0 / 0)      Functions: 33.33% (1 / 3)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/base.js");'use strict';global.tr.exportTo('tr.ui.annotations',function(){function AnnotationView(viewport,annotation){}AnnotationView.prototype={draw:function(ctx){throw new Error('Not implemented');}};return{AnnotationView:AnnotationView};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/annotations/comment_box_annotation_view.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/annotations/comment_box_annotation_view.js

Statements: 15.79% (6 / 38)      Branches: 0% (0 / 6)      Functions: 25% (1 / 4)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./annotation_view.js");'use strict';global.tr.exportTo('tr.ui.annotations',function(){function CommentBoxAnnotationView(viewport,annotation){this.viewport_=viewport;this.annotation_=annotation;this.textArea_=undefined;this.styleWidth=250;this.styleHeight=50;this.fontSize=10;this.rightOffset=50;this.topOffset=25;}CommentBoxAnnotationView.prototype={__proto__:tr.ui.annotations.AnnotationView.prototype,removeTextArea:function(){Polymer.dom(Polymer.dom(this.textArea_).parentNode).removeChild(this.textArea_);},draw:function(ctx){var coords=this.annotation_.location.toViewCoordinates(this.viewport_);if(coords.viewX<0){if(this.textArea_)this.textArea_.style.visibility='hidden';return;}if(!this.textArea_){this.textArea_=document.createElement('textarea');this.textArea_.style.position='absolute';this.textArea_.readOnly=true;this.textArea_.value=this.annotation_.text;this.textArea_.style.zIndex=1;Polymer.dom(Polymer.dom(ctx.canvas).parentNode).appendChild(this.textArea_);}this.textArea_.style.width=this.styleWidth+'px';this.textArea_.style.height=this.styleHeight+'px';this.textArea_.style.fontSize=this.fontSize+'px';this.textArea_.style.visibility='visible';this.textArea_.style.left=coords.viewX+ctx.canvas.getBoundingClientRect().left+this.rightOffset+'px';this.textArea_.style.top=coords.viewY-ctx.canvas.getBoundingClientRect().top-this.topOffset+'px';ctx.strokeStyle='rgb(0, 0, 0)';ctx.lineWidth=2;ctx.beginPath();tr.ui.b.drawLine(ctx,coords.viewX,coords.viewY-ctx.canvas.getBoundingClientRect().top,coords.viewX+this.rightOffset,coords.viewY-this.topOffset-ctx.canvas.getBoundingClientRect().top);ctx.stroke();}};return{CommentBoxAnnotationView:CommentBoxAnnotationView};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/annotations/rect_annotation_view.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/annotations/rect_annotation_view.js

Statements: 31.58% (6 / 19)      Branches: 0% (0 / 4)      Functions: 33.33% (1 / 3)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./annotation_view.js");'use strict';global.tr.exportTo('tr.ui.annotations',function(){function RectAnnotationView(viewport,annotation){this.viewport_=viewport;this.annotation_=annotation;}RectAnnotationView.prototype={__proto__:tr.ui.annotations.AnnotationView.prototype,draw:function(ctx){var dt=this.viewport_.currentDisplayTransform;var startCoords=this.annotation_.startLocation.toViewCoordinates(this.viewport_);var endCoords=this.annotation_.endLocation.toViewCoordinates(this.viewport_);var startY=startCoords.viewY-ctx.canvas.getBoundingClientRect().top;var sizeY=endCoords.viewY-startCoords.viewY;if(startY+sizeY<0){startY=sizeY;}else if(startY<0){startY=0;}ctx.fillStyle=this.annotation_.fillStyle;ctx.fillRect(startCoords.viewX,startY,endCoords.viewX-startCoords.viewX,sizeY);}};return{RectAnnotationView:RectAnnotationView};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/annotations/x_marker_annotation_view.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/annotations/x_marker_annotation_view.js

Statements: 42.86% (6 / 14)      Branches: 100% (0 / 0)      Functions: 33.33% (1 / 3)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./annotation_view.js");'use strict';global.tr.exportTo('tr.ui.annotations',function(){function XMarkerAnnotationView(viewport,annotation){this.viewport_=viewport;this.annotation_=annotation;}XMarkerAnnotationView.prototype={__proto__:tr.ui.annotations.AnnotationView.prototype,draw:function(ctx){var dt=this.viewport_.currentDisplayTransform;var viewX=dt.xWorldToView(this.annotation_.timestamp);ctx.beginPath();tr.ui.b.drawLine(ctx,viewX,0,viewX,ctx.canvas.height);ctx.strokeStyle=this.annotation_.strokeStyle;ctx.stroke();}};return{XMarkerAnnotationView:XMarkerAnnotationView};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/base/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/base/

Statements: 13.24% (27 / 204)      Branches: 1.25% (1 / 80)      Functions: 8.82% (3 / 34)      Lines: 100% (3 / 3)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/base/
File Statements Branches Functions Lines
overlay.js 7.34% (8 / 109) 2.38% (1 / 42) 5% (1 / 20) 100% (1 / 1)
ui.js 13.33% (8 / 60) 0% (0 / 30) 14.29% (1 / 7) 100% (1 / 1)
utils.js 31.43% (11 / 35) 0% (0 / 8) 14.29% (1 / 7) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/base/overlay.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/base/overlay.js

Statements: 7.34% (8 / 109)      Branches: 2.38% (1 / 42)      Functions: 5% (1 / 20)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/event.js");require("../../base/utils.js");require("./ui.js");require("./utils.js");'use strict';global.tr.exportTo('tr.ui.b',function(){Eif(tr.isHeadless)return{};return;var Overlay=tr.ui.b.define('overlay');Overlay.prototype={__proto__:HTMLDivElement.prototype,decorate:function(){Polymer.dom(this).classList.add('overlay');this.parentEl_=this.ownerDocument.body;this.visible_=false;this.userCanClose_=true;this.onKeyDown_=this.onKeyDown_.bind(this);this.onClick_=this.onClick_.bind(this);this.onFocusIn_=this.onFocusIn_.bind(this);this.onDocumentClick_=this.onDocumentClick_.bind(this);this.onClose_=this.onClose_.bind(this);this.addEventListener('visible-change',tr.ui.b.Overlay.prototype.onVisibleChange_.bind(this),true);var createShadowRoot=this.createShadowRoot||this.webkitCreateShadowRoot;this.shadow_=createShadowRoot.call(this);Polymer.dom(this.shadow_).appendChild(tr.ui.b.instantiateTemplate('#overlay-template',THIS_DOC));this.closeBtn_=Polymer.dom(this.shadow_).querySelector('close-button');this.closeBtn_.addEventListener('click',this.onClose_);Polymer.dom(this.shadow_).querySelector('overlay-frame').addEventListener('click',this.onClick_);this.observer_=new WebKitMutationObserver(this.didButtonBarMutate_.bind(this));this.observer_.observe(Polymer.dom(this.shadow_).querySelector('button-bar'),{childList:true});Object.defineProperty(this,'title',{get:function(){return Polymer.dom(Polymer.dom(this.shadow_).querySelector('title')).textContent;},set:function(title){Polymer.dom(Polymer.dom(this.shadow_).querySelector('title')).textContent=title;}});},set userCanClose(userCanClose){this.userCanClose_=userCanClose;this.closeBtn_.style.display=userCanClose?'block':'none';},get buttons(){return Polymer.dom(this.shadow_).querySelector('button-bar');},get visible(){return this.visible_;},set visible(newValue){if(this.visible_===newValue)return;this.visible_=newValue;var e=new tr.b.Event('visible-change');this.dispatchEvent(e);},onVisibleChange_:function(){this.visible_?this.show_():this.hide_();},show_:function(){Polymer.dom(this.parentEl_).appendChild(this);if(this.userCanClose_){this.addEventListener('keydown',this.onKeyDown_.bind(this));this.addEventListener('click',this.onDocumentClick_.bind(this));this.closeBtn_.addEventListener('click',this.onClose_);}this.parentEl_.addEventListener('focusin',this.onFocusIn_);this.tabIndex=0;var focusEl=undefined;var elList=Polymer.dom(this).querySelectorAll('button, input, list, select, a');if(elList.length>0){if(elList[0]===this.closeBtn_){if(elList.length>1)focusEl=elList[1];}else{focusEl=elList[0];}}if(focusEl===undefined)focusEl=this;focusEl.focus();},hide_:function(){Polymer.dom(this.parentEl_).removeChild(this);this.parentEl_.removeEventListener('focusin',this.onFocusIn_);if(this.closeBtn_)this.closeBtn_.removeEventListener('click',this.onClose_);document.removeEventListener('keydown',this.onKeyDown_);document.removeEventListener('click',this.onDocumentClick_);},onClose_:function(e){this.visible=false;if(e.type!='keydown'||e.type==='keydown'&&e.keyCode===27)e.stopPropagation();e.preventDefault();tr.b.dispatchSimpleEvent(this,'closeclick');},onFocusIn_:function(e){if(e.target===this)return;window.setTimeout(function(){this.focus();},0);e.preventDefault();e.stopPropagation();},didButtonBarMutate_:function(e){var hasButtons=this.buttons.children.length>0;if(hasButtons){Polymer.dom(this.shadow_).querySelector('button-bar').style.display=undefined;}else{Polymer.dom(this.shadow_).querySelector('button-bar').style.display='none';}},onKeyDown_:function(e){if(e.keyCode===9&&e.shiftKey&&e.target===this){e.preventDefault();return;}if(e.keyCode!==27)return;this.onClose_(e);},onClick_:function(e){e.stopPropagation();},onDocumentClick_:function(e){if(!this.userCanClose_)return;this.onClose_(e);}};Overlay.showError=function(msg,opt_err){var o=new Overlay();o.title='Error';Polymer.dom(o).textContent=msg;if(opt_err){var e=tr.b.normalizeException(opt_err);var stackDiv=document.createElement('pre');Polymer.dom(stackDiv).textContent=e.stack;stackDiv.style.paddingLeft='8px';stackDiv.style.margin=0;Polymer.dom(o).appendChild(stackDiv);}var b=document.createElement('button');Polymer.dom(b).textContent='OK';b.addEventListener('click',function(){o.visible=false;});Polymer.dom(o.buttons).appendChild(b);o.visible=true;return o;};return{Overlay:Overlay};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/base/ui.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/base/ui.js

Statements: 13.33% (8 / 60)      Branches: 0% (0 / 30)      Functions: 14.29% (1 / 7)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/base.js");'use strict';global.tr.exportTo('tr.ui.b',function(){function decorate(source,constr){var elements;if(typeof source=='string')elements=Polymer.dom(tr.doc).querySelectorAll(source);else elements=[source];for(var i=0,el;el=elements[i];i++){if(!(el instanceof constr))constr.decorate(el);}}function define(className,opt_parentConstructor,opt_tagNS){if(typeof className=='function'){throw new Error('Passing functions as className is deprecated. Please '+'use (className, opt_parentConstructor) to subclass');}var className=className.toLowerCase();if(opt_parentConstructor&&!opt_parentConstructor.tagName)throw new Error('opt_parentConstructor was not '+'created by tr.ui.b.define');var tagName=className;var tagNS=undefined;if(opt_parentConstructor){if(opt_tagNS)throw new Error('Must not specify tagNS if parentConstructor is given');var parent=opt_parentConstructor;while(parent&&parent.tagName){tagName=parent.tagName;tagNS=parent.tagNS;parent=parent.parentConstructor;}}else{tagNS=opt_tagNS;}function f(){if(opt_parentConstructor&&f.prototype.__proto__!=opt_parentConstructor.prototype){throw new Error(className+' prototye\'s __proto__ field is messed up. '+'It MUST be the prototype of '+opt_parentConstructor.tagName);}var el;if(tagNS===undefined)el=tr.doc.createElement(tagName);else el=tr.doc.createElementNS(tagNS,tagName);f.decorate.call(this,el,arguments);return el;}f.decorate=function(el){el.__proto__=f.prototype;el.decorate.apply(el,arguments[1]);el.constructor=f;};f.className=className;f.tagName=tagName;f.tagNS=tagNS;f.parentConstructor=opt_parentConstructor?opt_parentConstructor:undefined;f.toString=function(){if(!f.parentConstructor)return f.tagName;return f.parentConstructor.toString()+'::'+f.className;};return f;}function elementIsChildOf(el,potentialParent){if(el==potentialParent)return false;var cur=el;while(Polymer.dom(cur).parentNode){if(cur==potentialParent)return true;cur=Polymer.dom(cur).parentNode;}return false;};return{decorate:decorate,define:define,elementIsChildOf:elementIsChildOf};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/base/utils.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/ui/base/utils.js

Statements: 31.43% (11 / 35)      Branches: 0% (0 / 8)      Functions: 14.29% (1 / 7)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/base.js");require("../../base/rect.js");'use strict';global.tr.exportTo('tr.ui.b',function(){function instantiateTemplate(selector,doc){doc=doc||document;var el=Polymer.dom(doc).querySelector(selector);if(!el)throw new Error('Element not found');return doc.importNode(el.content,true);}function windowRectForElement(element){var position=[element.offsetLeft,element.offsetTop];var size=[element.offsetWidth,element.offsetHeight];var node=element.offsetParent;while(node){position[0]+=node.offsetLeft;position[1]+=node.offsetTop;node=node.offsetParent;}return tr.b.Rect.fromXYWH(position[0],position[1],size[0],size[1]);}function scrollIntoViewIfNeeded(el){var pr=el.parentElement.getBoundingClientRect();var cr=el.getBoundingClientRect();if(cr.top<pr.top){el.scrollIntoView(true);}else if(cr.bottom>pr.bottom){el.scrollIntoView(false);}}function extractUrlString(url){var extracted=url.replace(/url\((.*)\)/,'$1');extracted=extracted.replace(/\"(.*)\"/,'$1');return extracted;}function toThreeDigitLocaleString(value){return value.toLocaleString(undefined,{minimumFractionDigits:3,maximumFractionDigits:3});}function isUnknownElementName(name){return document.createElement(name)instanceof HTMLUnknownElement;}return{isUnknownElementName:isUnknownElementName,toThreeDigitLocaleString:toThreeDigitLocaleString,instantiateTemplate:instantiateTemplate,windowRectForElement:windowRectForElement,scrollIntoViewIfNeeded:scrollIntoViewIfNeeded,extractUrlString:extractUrlString};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/

Statements: 13.35% (59 / 442)      Branches: 2.86% (6 / 210)      Functions: 15.87% (10 / 63)      Lines: 100% (2 / 2)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/
File Statements Branches Functions Lines
histogram.js 13.33% (54 / 405) 3.19% (6 / 188) 16.36% (9 / 55) 100% (1 / 1)
numeric.js 13.51% (5 / 37) 0% (0 / 22) 12.5% (1 / 8) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/histogram.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/histogram.js

Statements: 13.33% (54 / 405)      Branches: 3.19% (6 / 188)      Functions: 16.36% (9 / 55)      Lines: 100% (1 / 1)      Ignored: none     

1 260  
"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("../base/iteration_helpers.js");require("../base/range.js");require("../base/running_statistics.js");require("../base/sorted_array_utils.js");require("../base/statistics.js");require("../base/unit.js");require("./diagnostics/diagnostic_map.js");require("./numeric.js");'use strict';global.tr.exportTo('tr.v',function(){var MAX_DIAGNOSTIC_MAPS=16;var DEFAULT_BOUNDARIES_FOR_UNIT=new Map();class HistogramBin{constructor(range){this.range=range;this.count=0;this.diagnosticMaps=[];}addSample(value){this.count+=1;}addDiagnosticMap(diagnostics){tr.b.Statistics.uniformlySampleStream(this.diagnosticMaps,this.count,diagnostics,MAX_DIAGNOSTIC_MAPS);}addBin(other){if(!this.range.equals(other.range))throw new Error('Merging incompatible Histogram bins.');tr.b.Statistics.mergeSampledStreams(this.diagnosticMaps,this.count,other.diagnosticMaps,other.count,MAX_DIAGNOSTIC_MAPS);this.count+=other.count;}fromDict(dict){this.count=dict[0];if(dict.length>1){for(var map of dict[1]){this.diagnosticMaps.push(tr.v.d.DiagnosticMap.fromDict(map));}}}asDict(){if(!this.diagnosticMaps.length){return[this.count];}return[this.count,this.diagnosticMaps.map(d=>d.asDict())];}}var DEFAULT_SUMMARY_OPTIONS=new Map([['avg',true],['geometricMean',false],['std',true],['count',true],['sum',true],['min',true],['max',true],['nans',false]]);class Histogram{constructor(name,unit,opt_binBoundaries){var binBoundaries=opt_binBoundaries;if(!binBoundaries){var baseUnit=unit.baseUnit?unit.baseUnit:unit;binBoundaries=DEFAULT_BOUNDARIES_FOR_UNIT.get(baseUnit.unitName);}this.guid_=undefined;this.binBoundariesDict_=binBoundaries.asDict();this.centralBins=[];this.description='';this.diagnostics=new tr.v.d.DiagnosticMap();this.maxCount_=0;this.name_=name;this.nanDiagnosticMaps=[];this.numNans=0;this.running=new tr.b.RunningStatistics();this.sampleValues_=[];this.shortName=undefined;this.summaryOptions=new Map(DEFAULT_SUMMARY_OPTIONS);this.summaryOptions.set('percentile',[]);this.unit=unit;this.underflowBin=new HistogramBin(tr.b.Range.fromExplicitRange(-Number.MAX_VALUE,binBoundaries.range.min));this.overflowBin=new HistogramBin(tr.b.Range.fromExplicitRange(binBoundaries.range.max,Number.MAX_VALUE));for(var range of binBoundaries.binRanges()){this.centralBins.push(new HistogramBin(range));}this.allBins=[this.underflowBin];for(var bin of this.centralBins)this.allBins.push(bin);this.allBins.push(this.overflowBin);this.maxNumSampleValues_=this.defaultMaxNumSampleValues_;}get maxNumSampleValues(){return this.maxNumSampleValues_;}set maxNumSampleValues(n){this.maxNumSampleValues_=n;tr.b.Statistics.uniformlySampleArray(this.sampleValues_,this.maxNumSampleValues_);}get name(){return this.name_;}get guid(){if(this.guid_===undefined)this.guid_=tr.b.GUID.allocateUUID4();return this.guid_;}set guid(guid){if(this.guid_!==undefined)throw new Error('Cannot reset guid');this.guid_=guid;}static fromDict(dict){var hist=new Histogram(dict.name,tr.b.Unit.fromJSON(dict.unit),HistogramBinBoundaries.fromDict(dict.binBoundaries));hist.guid=dict.guid;if(dict.shortName){hist.shortName=dict.shortName;}if(dict.description){hist.description=dict.description;}if(dict.diagnostics){hist.diagnostics.addDicts(dict.diagnostics);}if(dict.underflowBin){hist.underflowBin.fromDict(dict.underflowBin);}if(dict.overflowBin){hist.overflowBin.fromDict(dict.overflowBin);}if(dict.centralBins){if(dict.centralBins.length!==undefined){for(var i=0;i<dict.centralBins.length;++i){hist.centralBins[i].fromDict(dict.centralBins[i]);}}else{tr.b.iterItems(dict.centralBins,(i,binDict)=>{hist.centralBins[i].fromDict(binDict);});}}for(var bin of hist.allBins){hist.maxCount_=Math.max(hist.maxCount_,bin.count);}if(dict.running){hist.running=tr.b.RunningStatistics.fromDict(dict.running);}if(dict.summaryOptions){hist.customizeSummaryOptions(dict.summaryOptions);}if(dict.maxNumSampleValues!==undefined){hist.maxNumSampleValues=dict.maxNumSampleValues;}if(dict.sampleValues){hist.sampleValues_=dict.sampleValues;}if(dict.numNans){hist.numNans=dict.numNans;}if(dict.nanDiagnostics){for(var map of dict.nanDiagnostics){hist.nanDiagnosticMaps.push(tr.v.d.DiagnosticMap.fromDict(map));}}return hist;}static buildFromSamples(unit,samples){var boundaries=HistogramBinBoundaries.createFromSamples(samples);var result=new Histogram(unit,boundaries);result.maxNumSampleValues=1000;for(var sample of samples)result.addSample(sample);return result;}get numValues(){return tr.b.Statistics.sum(this.allBins,function(e){return e.count;});}get average(){return this.running.mean;}get standardDeviation(){return this.running.stddev;}get geometricMean(){return this.running.geometricMean;}get sum(){return this.running.sum;}get maxCount(){return this.maxCount_;}getDifferenceSignificance(other,opt_alpha){if(this.unit!==other.unit)throw new Error('Cannot compare Numerics with different units');if(this.unit.improvementDirection===tr.b.ImprovementDirection.DONT_CARE){return tr.b.Statistics.Significance.DONT_CARE;}if(!(other instanceof Histogram))throw new Error('Unable to compute a p-value');var testResult=tr.b.Statistics.mwu(this.sampleValues,other.sampleValues,opt_alpha);return testResult.significance;}getApproximatePercentile(percent){if(!(percent>=0&&percent<=1))throw new Error('percent must be [0,1]');if(this.numValues==0)return 0;var valuesToSkip=Math.floor((this.numValues-1)*percent);for(var i=0;i<this.allBins.length;i++){var bin=this.allBins[i];valuesToSkip-=bin.count;if(valuesToSkip<0){if(bin===this.underflowBin)return bin.range.max;else if(bin===this.overflowBin)return bin.range.min;else return bin.range.center;}}throw new Error('Unreachable');}getBinForValue(value){var binIndex=tr.b.findHighIndexInSortedArray(this.allBins,b=>value<b.range.max?-1:1);return this.allBins[binIndex]||this.overflowBin;}addSample(value,opt_diagnostics){if(opt_diagnostics&&!(opt_diagnostics instanceof tr.v.d.DiagnosticMap))opt_diagnostics=tr.v.d.DiagnosticMap.fromObject(opt_diagnostics);if(typeof value!=='number'||isNaN(value)){this.numNans++;if(opt_diagnostics){tr.b.Statistics.uniformlySampleStream(this.nanDiagnosticMaps,this.numNans,opt_diagnostics,MAX_DIAGNOSTIC_MAPS);}}else{this.running.add(value);var bin=this.getBinForValue(value);bin.addSample(value);if(opt_diagnostics)bin.addDiagnosticMap(opt_diagnostics);if(bin.count>this.maxCount_)this.maxCount_=bin.count;}tr.b.Statistics.uniformlySampleStream(this.sampleValues_,this.numValues+this.numNans,value,this.maxNumSampleValues);}sampleValuesInto(samples){for(var sampleValue of this.sampleValues)samples.push(sampleValue);}canAddHistogram(other){if(this.unit!==other.unit)return false;if(this.allBins.length!==other.allBins.length)return false;for(var i=0;i<this.allBins.length;++i)if(!this.allBins[i].range.equals(other.allBins[i].range))return false;return true;}addHistogram(other){if(!this.canAddHistogram(other)){throw new Error('Merging incompatible Histograms');}tr.b.Statistics.mergeSampledStreams(this.nanDiagnosticMaps,this.numNans,other.nanDiagnosticMaps,other.numNans,MAX_DIAGNOSTIC_MAPS);tr.b.Statistics.mergeSampledStreams(this.sampleValues,this.numValues,other.sampleValues,other.numValues,tr.b.Statistics.mean([this.maxNumSampleValues,other.maxNumSampleValues]));this.numNans+=other.numNans;this.running=this.running.merge(other.running);for(var i=0;i<this.allBins.length;++i){this.allBins[i].addBin(other.allBins[i]);}}customizeSummaryOptions(summaryOptions){tr.b.iterItems(summaryOptions,(key,value)=>this.summaryOptions.set(key,value));}get statisticsScalars(){function statNameToKey(stat){switch(stat){case'std':return'stddev';case'avg':return'mean';}return stat;}function percentToString(percent){if(percent<0||percent>1)throw new Error('Percent must be between 0.0 and 1.0');switch(percent){case 0:return'000';case 1:return'100';}var str=percent.toString();if(str[1]!=='.')throw new Error('Unexpected percent');str=str+'0'.repeat(Math.max(4-str.length,0));if(str.length>4)str=str.slice(0,4)+'_'+str.slice(4);return'0'+str.slice(2);}var results=new Map();for(var _ref of this.summaryOptions){var _ref2=_slicedToArray(_ref,2);var stat=_ref2[0];var option=_ref2[1];if(!option){continue;}if(stat==='percentile'){for(var percent of option){var percentile=this.getApproximatePercentile(percent);results.set('pct_'+percentToString(percent),new tr.v.ScalarNumeric(this.unit,percentile));}}else if(stat==='nans'){results.set('nans',new tr.v.ScalarNumeric(tr.b.Unit.byName.count_smallerIsBetter,this.numNans));}else{var statUnit=stat==='count'?tr.b.Unit.byName.count_smallerIsBetter:this.unit;var key=statNameToKey(stat);var statValue=this.running[key];if(typeof statValue==='number'){results.set(stat,new tr.v.ScalarNumeric(statUnit,statValue));}}}return results;}get sampleValues(){return this.sampleValues_;}clone(){return Histogram.fromDict(this.asDict());}cloneEmpty(){var binBoundaries=HistogramBinBoundaries.fromDict(this.binBoundariesDict_);return new Histogram(this.name,this.unit,binBoundaries);}asDict(){var dict={};dict.binBoundaries=this.binBoundariesDict_;dict.name=this.name;dict.unit=this.unit.asJSON();dict.guid=this.guid;if(this.shortName){dict.shortName=this.shortName;}if(this.description){dict.description=this.description;}if(this.diagnostics.size){dict.diagnostics=this.diagnostics.asDict();}if(this.maxNumSampleValues!==this.defaultMaxNumSampleValues_){dict.maxNumSampleValues=this.maxNumSampleValues;}if(this.numNans){dict.numNans=this.numNans;}if(this.nanDiagnosticMaps.length){dict.nanDiagnostics=this.nanDiagnosticMaps.map(dm=>dm.asDict());}if(this.underflowBin.count){dict.underflowBin=this.underflowBin.asDict();}if(this.overflowBin.count){dict.overflowBin=this.overflowBin.asDict();}if(this.numValues){dict.sampleValues=this.sampleValues.slice();dict.running=this.running.asDict();dict.centralBins=this.centralBinsAsDict_();}var summaryOptions={};var anyOverriddenSummaryOptions=false;for(var _ref3 of this.summaryOptions){var _ref4=_slicedToArray(_ref3,2);var name=_ref4[0];var option=_ref4[1];if(name==='percentile'){if(option.length===0){continue;}option=option.slice();}else if(option===DEFAULT_SUMMARY_OPTIONS.get(name)){continue;}summaryOptions[name]=option;anyOverriddenSummaryOptions=true;}if(anyOverriddenSummaryOptions){dict.summaryOptions=summaryOptions;}return dict;}centralBinsAsDict_(){var numCentralBins=this.centralBins.length;var emptyBins=0;for(var i=0;i<numCentralBins;++i){if(this.centralBins[i].count===0){++emptyBins;}}if(emptyBins===numCentralBins){return undefined;}if(emptyBins>numCentralBins/2){var centralBinsDict={};for(var i=0;i<numCentralBins;++i){var bin=this.centralBins[i];if(bin.count>0){centralBinsDict[i]=bin.asDict();}}return centralBinsDict;}var centralBinsArray=[];for(var i=0;i<numCentralBins;++i){centralBinsArray.push(this.centralBins[i].asDict());}return centralBinsArray;}get defaultMaxNumSampleValues_(){return this.allBins.length*10;}}var HISTOGRAM_BIN_BOUNDARIES_CACHE=new Map();class HistogramBinBoundaries{static createLinear(min,max,numBins){return new HistogramBinBoundaries(min).addLinearBins(max,numBins);}static createExponential(min,max,numBins){return new HistogramBinBoundaries(min).addExponentialBins(max,numBins);}static createWithBoundaries(binBoundaries){var builder=new HistogramBinBoundaries(binBoundaries[0]);for(var boundary of binBoundaries.slice(1))builder.addBinBoundary(boundary);return builder;}static createFromSamples(samples){var range=new tr.b.Range();for(var sample of samples)if(!isNaN(Math.max(sample)))range.addValue(sample);if(range.isEmpty)range.addValue(1);if(range.min===range.max)range.addValue(range.min-1);var numBins=Math.ceil(Math.sqrt(samples.length));var builder=new HistogramBinBoundaries(range.min);builder.addLinearBins(range.max,numBins);return builder;}constructor(minBinBoundary){this.boundaries_=undefined;this.builder_=[minBinBoundary];this.range_=new tr.b.Range();this.range_.addValue(minBinBoundary);}get range(){return this.range_;}asDict(){return this.builder_.slice();}static fromDict(dict){var cacheKey=JSON.stringify(dict);if(HISTOGRAM_BIN_BOUNDARIES_CACHE.has(cacheKey)){return HISTOGRAM_BIN_BOUNDARIES_CACHE.get(cacheKey);}var binBoundaries=new HistogramBinBoundaries(dict[0]);for(var slice of dict.slice(1)){if(!(slice instanceof Array)){binBoundaries.addBinBoundary(slice);continue;}switch(slice[0]){case HistogramBinBoundaries.SLICE_TYPE.LINEAR:binBoundaries.addLinearBins(slice[1],slice[2]);break;case HistogramBinBoundaries.SLICE_TYPE.EXPONENTIAL:binBoundaries.addExponentialBins(slice[1],slice[2]);break;default:throw new Error('Unrecognized HistogramBinBoundaries slice type');}}HISTOGRAM_BIN_BOUNDARIES_CACHE.set(cacheKey,binBoundaries);return binBoundaries;}*binRanges(){if(this.boundaries_===undefined){this.build_();}for(var i=0;i<this.boundaries_.length-1;++i){yield tr.b.Range.fromExplicitRange(this.boundaries_[i],this.boundaries_[i+1]);}}build_(){if(typeof this.builder_[0]!=='number'){throw new Error('Invalid start of builder_');}this.boundaries_=[this.builder_[0]];for(var slice of this.builder_.slice(1)){if(!(slice instanceof Array)){this.boundaries_.push(slice);continue;}var nextMaxBinBoundary=slice[1];var binCount=slice[2];var curMaxBinBoundary=this.boundaries_[this.boundaries_.length-1];switch(slice[0]){case HistogramBinBoundaries.SLICE_TYPE.LINEAR:var binWidth=(nextMaxBinBoundary-curMaxBinBoundary)/binCount;for(var i=1;i<binCount;i++){var boundary=curMaxBinBoundary+i*binWidth;this.boundaries_.push(boundary);}break;case HistogramBinBoundaries.SLICE_TYPE.EXPONENTIAL:var binExponentWidth=Math.log(nextMaxBinBoundary/curMaxBinBoundary)/binCount;for(var i=1;i<binCount;i++){var boundary=curMaxBinBoundary*Math.exp(i*binExponentWidth);this.boundaries_.push(boundary);}break;default:throw new Error('Unrecognized HistogramBinBoundaries slice type');}this.boundaries_.push(nextMaxBinBoundary);}}addBinBoundary(nextMaxBinBoundary){Iif(nextMaxBinBoundary<=this.range.max){throw new Error('The added max bin boundary must be larger than '+'the current max boundary');}this.boundaries_=undefined;this.builder_.push(nextMaxBinBoundary);this.range.addValue(nextMaxBinBoundary);return this;}addLinearBins(nextMaxBinBoundary,binCount){Iif(binCount<=0)throw new Error('Bin count must be positive');Iif(nextMaxBinBoundary<=this.range.max){throw new Error('The new max bin boundary must be greater than '+'the previous max bin boundary');}this.boundaries_=undefined;this.builder_.push([HistogramBinBoundaries.SLICE_TYPE.LINEAR,nextMaxBinBoundary,binCount]);this.range.addValue(nextMaxBinBoundary);return this;}addExponentialBins(nextMaxBinBoundary,binCount){Iif(binCount<=0){throw new Error('Bin count must be positive');}Iif(this.range.max<=0){throw new Error('Current max bin boundary must be positive');}Iif(this.range.max>=nextMaxBinBoundary){throw new Error('The last added max boundary must be greater than '+'the current max boundary boundary');}this.boundaries_=undefined;this.builder_.push([HistogramBinBoundaries.SLICE_TYPE.EXPONENTIAL,nextMaxBinBoundary,binCount]);this.range.addValue(nextMaxBinBoundary);return this;}}HistogramBinBoundaries.SLICE_TYPE={LINEAR:0,EXPONENTIAL:1};DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.timeDurationInMs.unitName,HistogramBinBoundaries.createExponential(1e-3,1e6,1e2));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.timeStampInMs.unitName,HistogramBinBoundaries.createLinear(0,1e10,1e3));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.normalizedPercentage.unitName,HistogramBinBoundaries.createLinear(0,1.0,20));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.sizeInBytes.unitName,HistogramBinBoundaries.createExponential(1,1e12,1e2));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.energyInJoules.unitName,HistogramBinBoundaries.createExponential(1e-3,1e3,50));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.powerInWatts.unitName,HistogramBinBoundaries.createExponential(1e-3,1,50));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.unitlessNumber.unitName,HistogramBinBoundaries.createExponential(1e-3,1e3,50));DEFAULT_BOUNDARIES_FOR_UNIT.set(tr.b.Unit.byName.count.unitName,HistogramBinBoundaries.createExponential(1,1e3,20));return{Histogram:Histogram,HistogramBinBoundaries:HistogramBinBoundaries};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/numeric.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/numeric.js

Statements: 13.51% (5 / 37)      Branches: 0% (0 / 22)      Functions: 12.5% (1 / 8)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../base/iteration_helpers.js");require("../base/unit.js");'use strict';global.tr.exportTo('tr.v',function(){class NumericBase{constructor(unit){if(!(unit instanceof tr.b.Unit))throw new Error('Expected provided unit to be instance of Unit');this.unit=unit;}asDict(){var d={unit:this.unit.asJSON()};this.asDictInto_(d);return d;}static fromDict(d){if(d.type==='scalar')return ScalarNumeric.fromDict(d);throw new Error('Not implemented');}}class ScalarNumeric extends NumericBase{constructor(unit,value){if(!(unit instanceof tr.b.Unit))throw new Error('Expected Unit');if(!(typeof value=='number'))throw new Error('Expected value to be number');super(unit);this.value=value;}asDictInto_(d){d.type='scalar';if(this.value===Infinity)d.value='Infinity';else if(this.value===-Infinity)d.value='-Infinity';else if(isNaN(this.value))d.value='NaN';else d.value=this.value;}toString(){return this.unit.format(this.value);}static fromDict(d){if(typeof d.value==='string'){if(d.value==='-Infinity'){d.value=-Infinity;}else if(d.value==='Infinity'){d.value=Infinity;}else if(d.value==='NaN'){d.value=NaN;}}return new ScalarNumeric(tr.b.Unit.fromJSON(d.unit),d.value);}}return{NumericBase:NumericBase,ScalarNumeric:ScalarNumeric};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/

Statements: 19.96% (96 / 481)      Branches: 2.19% (4 / 183)      Functions: 16.98% (18 / 106)      Lines: 100% (12 / 12)      Ignored: none     

All files » node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/
File Statements Branches Functions Lines
breakdown.js 15.09% (8 / 53) 0% (0 / 24) 20% (2 / 10) 100% (1 / 1)
diagnostic.js 55% (11 / 20) 57.14% (4 / 7) 40% (2 / 5) 100% (1 / 1)
diagnostic_map.js 24.56% (14 / 57) 0% (0 / 18) 18.18% (2 / 11) 100% (1 / 1)
event_ref.js 40% (4 / 10) 100% (0 / 0) 50% (1 / 2) 100% (1 / 1)
generic.js 55.56% (5 / 9) 100% (0 / 0) 25% (1 / 4) 100% (1 / 1)
iteration_info.js 8.54% (7 / 82) 0% (0 / 34) 4.35% (1 / 23) 100% (1 / 1)
related_event_set.js 15.87% (10 / 63) 0% (0 / 26) 16.67% (2 / 12) 100% (1 / 1)
related_histogram_breakdown.js 15% (6 / 40) 0% (0 / 20) 14.29% (1 / 7) 100% (1 / 1)
related_value_map.js 15.63% (10 / 64) 0% (0 / 24) 14.29% (2 / 14) 100% (1 / 1)
related_value_set.js 15.38% (10 / 65) 0% (0 / 28) 16.67% (2 / 12) 100% (1 / 1)
scalar.js 50% (6 / 12) 0% (0 / 2) 25% (1 / 4) 100% (1 / 1)
value_ref.js 83.33% (5 / 6) 100% (0 / 0) 50% (1 / 2) 100% (1 / 1)
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/breakdown.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/breakdown.js

Statements: 15.09% (8 / 53)      Branches: 0% (0 / 24)      Functions: 20% (2 / 10)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("./related_value_map.js");'use strict';global.tr.exportTo('tr.v.d',function(){class Breakdown extends tr.v.d.Diagnostic{constructor(){super();this.values_=new Map();this.colorScheme=undefined;}set(name,value){if(typeof name!=='string'||typeof value!=='number'){throw new Error('Breakdown maps from strings to numbers');}this.values_.set(name,value);}get(name){return this.values_.get(name)||0;}*[Symbol.iterator](){for(var pair of this.values_)yield pair;}asDictInto_(d){d.values={};for(var _ref of this){var _ref2=_slicedToArray(_ref,2);var name=_ref2[0];var value=_ref2[1];d.values[name]=value;}if(this.colorScheme)d.colorScheme=this.colorScheme;}static fromDict(d){var breakdown=new Breakdown();tr.b.iterItems(d.values,(name,value)=>breakdown.set(name,value));if(d.colorScheme)breakdown.colorScheme=d.colorScheme;return breakdown;}}tr.v.d.Diagnostic.register(Breakdown,{elementName:'tr-v-ui-breakdown-span'});return{Breakdown:Breakdown};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/diagnostic.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/diagnostic.js

Statements: 55% (11 / 20)      Branches: 57.14% (4 / 7)      Functions: 40% (2 / 5)      Lines: 100% (1 / 1)      Ignored: none     

1 28  
"use strict";require("../../base/extension_registry.js");'use strict';global.tr.exportTo('tr.v.d',function(){class Diagnostic{asDict(){var result={type:this.constructor.name};this.asDictInto_(result);return result;}asDictInto_(d){throw new Error('Abstract virtual method');}static fromDict(d){var typeInfo=Diagnostic.findTypeInfoWithName(d.type);if(!typeInfo)throw new Error('Unrecognized diagnostic type: '+d.type);return typeInfo.constructor.fromDict(d);}}var options=new tr.b.ExtensionRegistryOptions(tr.b.BASIC_REGISTRY_MODE);options.defaultMetadata={};options.mandatoryBaseClass=Diagnostic;tr.b.decorateExtensionRegistry(Diagnostic,options);Diagnostic.addEventListener('will-register',function(e){var constructor=e.typeInfo.constructor;Iif(!(constructor.fromDict instanceof Function)||constructor.fromDict===Diagnostic.fromDict||constructor.fromDict.length!==1){throw new Error('Diagnostics must define fromDict(d)');}});return{Diagnostic:Diagnostic};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/diagnostic_map.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/diagnostic_map.js

Statements: 24.56% (14 / 57)      Branches: 0% (0 / 18)      Functions: 18.18% (2 / 11)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("./breakdown.js");require("./generic.js");require("./iteration_info.js");require("./related_event_set.js");require("./related_histogram_breakdown.js");require("./related_value_map.js");require("./related_value_set.js");require("./scalar.js");'use strict';global.tr.exportTo('tr.v.d',function(){class DiagnosticMap extends Map{set(name,diagnostic){if(typeof name!=='string')throw new Error('name must be string, not '+name);if(!(diagnostic instanceof tr.v.d.Diagnostic))throw new Error('Must be instanceof Diagnostic: '+diagnostic);Map.prototype.set.call(this,name,diagnostic);}addDicts(dict){tr.b.iterItems(dict,function(name,diagnosticDict){this.set(name,tr.v.d.Diagnostic.fromDict(diagnosticDict));},this);}asDict(){var dict={};for(var _ref of this){var _ref2=_slicedToArray(_ref,2);var name=_ref2[0];var diagnostic=_ref2[1];dict[name]=diagnostic.asDict();}return dict;}static fromDict(d){var diagnostics=new DiagnosticMap();diagnostics.addDicts(d);return diagnostics;}static fromObject(obj){var diagnostics=new DiagnosticMap();tr.b.iterItems(obj,function(name,diagnostic){diagnostics.set(name,diagnostic);});return diagnostics;}}return{DiagnosticMap:DiagnosticMap};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/event_ref.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/event_ref.js

Statements: 40% (4 / 10)      Branches: 100% (0 / 0)      Functions: 50% (1 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/guid.js");'use strict';global.tr.exportTo('tr.v.d',function(){class EventRef{constructor(event){this.stableId=event.stableId;this.title=event.title;this.start=event.start;this.duration=event.duration;this.end=this.start+this.duration;this.guid=tr.b.GUID.allocateSimple();}}return{EventRef:EventRef};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/generic.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/generic.js

Statements: 55.56% (5 / 9)      Branches: 100% (0 / 0)      Functions: 25% (1 / 4)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./diagnostic.js");'use strict';global.tr.exportTo('tr.v.d',function(){class Generic extends tr.v.d.Diagnostic{constructor(value){super();this.value=value;}asDictInto_(d){d.value=this.value;}static fromDict(d){return new Generic(d.value);}}tr.v.d.Diagnostic.register(Generic,{elementName:'tr-v-ui-generic-diagnostic-span'});return{Generic:Generic};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/iteration_info.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/iteration_info.js

Statements: 8.54% (7 / 82)      Branches: 0% (0 / 34)      Functions: 4.35% (1 / 23)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/utils.js");require("./diagnostic.js");'use strict';global.tr.exportTo('tr.v.d',function(){class IterationInfo extends tr.v.d.Diagnostic{constructor(opt_info){super();this.benchmarkName_='';this.benchmarkStart_=undefined;this.label_='';this.osVersion_='';this.productVersion_='';this.storyDisplayName_='';this.storyGroupingKeys_={};this.storyRepeatCounter_=undefined;this.storyUrl_='';this.storysetRepeatCounter_=undefined;if(opt_info)this.addInfo(opt_info);}addInfo(info){if(info.benchmarkName)this.benchmarkName_=info.benchmarkName;if(info.benchmarkStartMs)this.benchmarkStart_=new Date(info.benchmarkStartMs);if(info.label)this.label_=info.label;if(info.storyDisplayName)this.storyDisplayName_=info.storyDisplayName;if(info.storyGroupingKeys)this.storyGroupingKeys_=info.storyGroupingKeys;if(info.storyRepeatCounter!==undefined)this.storyRepeatCounter_=info.storyRepeatCounter;if(info.storyUrl)this.storyUrl_=info.storyUrl;if(info.storysetRepeatCounter!==undefined)this.storysetRepeatCounter_=info.storysetRepeatCounter;if(info['os-version'])this.osVersion_=info['os-version'];if(info['product-version'])this.productVersion_=info['product-version'];}addToValue(value){value.diagnostics.set(IterationInfo.NAME,this);}static getFromValue(value){return value.diagnostics.get(IterationInfo.NAME);}asDictInto_(d){d.benchmarkName=this.benchmarkName;if(this.benchmarkStart)d.benchmarkStartMs=this.benchmarkStart.getTime();d.label=this.label;d.storyDisplayName=this.storyDisplayName;d.storyGroupingKeys=this.storyGroupingKeys;d.storyRepeatCounter=this.storyRepeatCounter;d.storyUrl=this.storyUrl;d.storysetRepeatCounter=this.storysetRepeatCounter;d['os-version']=this.osVersion;d['product-version']=this.productVersion;}static fromDict(d){var info=new IterationInfo();info.addInfo(d);return info;}get displayLabel(){if(this.label)return this.label;return this.benchmarkName+' '+this.benchmarkStartString;}get osVersion(){return this.osVersion_;}get productVersion(){return this.productVersion_;}get benchmarkName(){return this.benchmarkName_;}get label(){return this.label_;}get storyGroupingKeys(){return this.storyGroupingKeys_;}get storyDisplayName(){return this.storyDisplayName_;}get storyUrl(){return this.storyUrl_;}get storyRepeatCounter(){return this.storyRepeatCounter_;}get storyRepeatCounterLabel(){return'story repeat '+this.storyRepeatCounter;}get storysetRepeatCounter(){return this.storysetRepeatCounter_;}get storysetRepeatCounterLabel(){return'storyset repeat '+this.storysetRepeatCounter;}get benchmarkStart(){return this.benchmarkStart_;}get benchmarkStartString(){if(this.benchmarkStart_===undefined)return'';return tr.b.formatDate(this.benchmarkStart);}static getField(value,fieldName,defaultValue){var iteration=tr.v.d.IterationInfo.getFromValue(value);if(!(iteration instanceof tr.v.d.IterationInfo)||!iteration[fieldName]){return defaultValue;}return iteration[fieldName];}static getStoryGroupingKeyLabel(value,storyGroupingKey){var iteration=tr.v.d.IterationInfo.getFromValue(value);if(!(iteration instanceof tr.v.d.IterationInfo))return storyGroupingKey+': undefined';return storyGroupingKey+': '+iteration.storyGroupingKeys[storyGroupingKey];}}IterationInfo.NAME='iteration';tr.v.d.Diagnostic.register(IterationInfo,{elementName:'tr-v-ui-iteration-info-span'});return{IterationInfo:IterationInfo};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/related_event_set.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/related_event_set.js

Statements: 15.87% (10 / 63)      Branches: 0% (0 / 26)      Functions: 16.67% (2 / 12)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("../../model/event_set.js");require("./diagnostic.js");require("./event_ref.js");'use strict';global.tr.exportTo('tr.v.d',function(){class RelatedEventSet extends tr.v.d.Diagnostic{constructor(opt_events){super();this.eventsByStableId_=new Map();if(opt_events){if(opt_events instanceof tr.model.EventSet||opt_events instanceof Array){for(var event of opt_events)this.add(event);}else{this.add(opt_events);}}}add(event){this.eventsByStableId_.set(event.stableId,event);}has(event){return this.eventsByStableId_.has(event.stableId);}get length(){return this.eventsByStableId_.size;}*[Symbol.iterator](){for(var _ref of this.eventsByStableId_){var _ref2=_slicedToArray(_ref,2);var stableId=_ref2[0];var event=_ref2[1];yield event;}}resolve(model,opt_required){for(var _ref3 of this.eventsByStableId_){var _ref4=_slicedToArray(_ref3,2);var stableId=_ref4[0];var event=_ref4[1];if(!(event instanceof tr.v.d.EventRef))continue;event=model.getEventByStableId(stableId);if(event instanceof tr.model.Event)this.eventsByStableId_.set(stableId,event);else if(opt_required)throw new Error('Unable to find Event '+stableId);}}asDictInto_(d){d.events=[];for(var event of this){d.events.push({stableId:event.stableId,title:event.title,start:event.start,duration:event.duration});}}static fromDict(d){return new RelatedEventSet(d.events.map(event=>new tr.v.d.EventRef(event)));}}tr.v.d.Diagnostic.register(RelatedEventSet,{elementName:'tr-v-ui-related-event-set-span'});return{RelatedEventSet:RelatedEventSet};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/related_histogram_breakdown.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/related_histogram_breakdown.js

Statements: 15% (6 / 40)      Branches: 0% (0 / 20)      Functions: 14.29% (1 / 7)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./related_value_map.js");'use strict';global.tr.exportTo('tr.v.d',function(){var COLOR_SCHEME_CHROME_USER_FRIENDLY_CATEGORY_DRIVER='ChromeUserFriendlyCategory';class RelatedHistogramBreakdown extends tr.v.d.RelatedValueMap{constructor(){super();this.colorScheme=undefined;}set(name,value){if(!(value instanceof tr.v.d.ValueRef)){if(!(value instanceof tr.v.Histogram)){throw new Error('RelatedHistogramBreakdown can only contain Histograms');}if(value.name.indexOf(name)!==value.name.length-name.length){throw new Error('RelatedHistogramBreakdown name must be a suffix of value.name');}if(this.length>0&&value.unit!==tr.b.getFirstElement(this)[1].unit){throw new Error('Units mismatch',tr.b.getFirstElement(this)[1].unit,value.unit);}}tr.v.d.RelatedValueMap.prototype.set.call(this,name,value);}asDictInto_(d){tr.v.d.RelatedValueMap.prototype.asDictInto_.call(this,d);if(this.colorScheme)d.colorScheme=this.colorScheme;}static fromDict(d){var diagnostic=new RelatedHistogramBreakdown();tr.b.iterItems(d.values,function(name,guid){diagnostic.set(name,new tr.v.d.ValueRef(guid));});if(d.colorScheme)diagnostic.colorScheme=d.colorScheme;return diagnostic;}static buildFromEvents(values,namePrefix,events,categoryForEvent,unit,opt_sampleForEvent,opt_binBoundaries,opt_this){var sampleForEvent=opt_sampleForEvent||(event=>event.cpuSelfTime);var diagnostic=new RelatedHistogramBreakdown();for(var event of events){var sample=sampleForEvent.call(opt_this,event);if(sample===undefined)continue;var eventCategory=categoryForEvent.call(opt_this,event);var value=diagnostic.get(eventCategory);if(value===undefined){value=new tr.v.Histogram(namePrefix+eventCategory,unit,opt_binBoundaries);values.addHistogram(value);diagnostic.set(eventCategory,value);}value.addSample(sample,{relatedEvents:new tr.v.d.RelatedEventSet([event])});}return diagnostic;}}tr.v.d.Diagnostic.register(RelatedHistogramBreakdown,{elementName:'tr-v-ui-breakdown-span'});return{COLOR_SCHEME_CHROME_USER_FRIENDLY_CATEGORY_DRIVER:COLOR_SCHEME_CHROME_USER_FRIENDLY_CATEGORY_DRIVER,RelatedHistogramBreakdown:RelatedHistogramBreakdown};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/related_value_map.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/related_value_map.js

Statements: 15.63% (10 / 64)      Branches: 0% (0 / 24)      Functions: 14.29% (2 / 14)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("../../base/iteration_helpers.js");require("./diagnostic.js");require("./value_ref.js");'use strict';global.tr.exportTo('tr.v.d',function(){class RelatedValueMap extends tr.v.d.Diagnostic{constructor(){super();this.valuesByName_=new Map();}get(name){return this.valuesByName_.get(name);}set(name,value){if(!(value instanceof tr.v.Histogram)&&!(value instanceof tr.v.d.ValueRef))throw new Error('Must be instanceof Histogram or ValueRef: '+value);this.valuesByName_.set(name,value);}add(value){this.set(value.name,value);}get length(){return this.valuesByName_.size;}*[Symbol.iterator](){for(var pair of this.valuesByName_)yield pair;}resolve(valueSet,opt_required){for(var _ref of this){var _ref2=_slicedToArray(_ref,2);var name=_ref2[0];var value=_ref2[1];if(!(value instanceof tr.v.d.ValueRef))continue;var guid=value.guid;value=valueSet.lookup(guid);if(value instanceof tr.v.Histogram)this.valuesByName_.set(name,value);else if(opt_required)throw new Error('Unable to find Histogram '+guid);}}asDictInto_(d){d.values={};for(var _ref3 of this){var _ref4=_slicedToArray(_ref3,2);var name=_ref4[0];var value=_ref4[1];d.values[name]=value.guid;}}static fromDict(d){var map=new RelatedValueMap();tr.b.iterItems(d.values,function(name,guid){map.set(name,new tr.v.d.ValueRef(guid));});return map;}}tr.v.d.Diagnostic.register(RelatedValueMap,{elementName:'tr-v-ui-related-value-map-span'});return{RelatedValueMap:RelatedValueMap};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/related_value_set.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/related_value_set.js

Statements: 15.38% (10 / 65)      Branches: 0% (0 / 28)      Functions: 16.67% (2 / 12)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"])_i["return"]();}finally{if(_d)throw _e;}}return _arr;}return function(arr,i){if(Array.isArray(arr)){return arr;}else if(Symbol.iterator in Object(arr)){return sliceIterator(arr,i);}else{throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();require("../../base/iteration_helpers.js");require("./diagnostic.js");require("./value_ref.js");'use strict';global.tr.exportTo('tr.v.d',function(){class RelatedValueSet extends tr.v.d.Diagnostic{constructor(opt_values){super();this.valuesByGuid_=new Map();if(opt_values)for(var value of opt_values)this.add(value);}add(value){if(!(value instanceof tr.v.Histogram)&&!(value instanceof tr.v.d.ValueRef))throw new Error('Must be instanceof Histogram or ValueRef: '+value);if(this.valuesByGuid_.get(value.guid))throw new Error('Tried to add same value twice');this.valuesByGuid_.set(value.guid,value);}has(value){return this.valuesByGuid_.has(value.guid);}get length(){return this.valuesByGuid_.size;}*[Symbol.iterator](){for(var _ref of this.valuesByGuid_){var _ref2=_slicedToArray(_ref,2);var guid=_ref2[0];var value=_ref2[1];yield value;}}resolve(valueSet,opt_required){for(var _ref3 of this.valuesByGuid_){var _ref4=_slicedToArray(_ref3,2);var guid=_ref4[0];var value=_ref4[1];if(!(value instanceof tr.v.d.ValueRef))continue;value=valueSet.lookup(guid);if(value instanceof tr.v.Histogram)this.valuesByGuid_.set(guid,value);else if(opt_required)throw new Error('Unable to find Histogram '+guid);}}asDictInto_(d){d.guids=[];for(var value of this)d.guids.push(value.guid);}static fromDict(d){return new RelatedValueSet(d.guids.map(guid=>new tr.v.d.ValueRef(guid)));}}tr.v.d.Diagnostic.register(RelatedValueSet,{elementName:'tr-v-ui-related-value-set-span'});return{RelatedValueSet:RelatedValueSet};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/scalar.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/scalar.js

Statements: 50% (6 / 12)      Branches: 0% (0 / 2)      Functions: 25% (1 / 4)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("./diagnostic.js");require("../numeric.js");'use strict';global.tr.exportTo('tr.v.d',function(){class Scalar extends tr.v.d.Diagnostic{constructor(value){super();if(!(value instanceof tr.v.ScalarNumeric))throw new Error("expected ScalarNumeric");this.value=value;}asDictInto_(d){d.value=this.value.asDict();}static fromDict(d){return new Scalar(tr.v.ScalarNumeric.fromDict(d.value));}}tr.v.d.Diagnostic.register(Scalar,{elementName:'tr-v-ui-scalar-diagnostic-span'});return{Scalar:Scalar};});
 
Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/value_ref.js

npmtest-lighthouse (v0.0.1)

Code coverage report for node-npmtest-lighthouse/node_modules/lighthouse/lighthouse-core/third_party/traceviewer-js/value/diagnostics/value_ref.js

Statements: 83.33% (5 / 6)      Branches: 100% (0 / 0)      Functions: 50% (1 / 2)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
"use strict";require("../../base/base.js");'use strict';global.tr.exportTo('tr.v.d',function(){function ValueRef(guid){this.guid=guid;}return{ValueRef:ValueRef};});